feat: drop a card on the machine it prints on; Pagamentos says who paid
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 57s

- Imprimindo: every active machine has its lane, and a card dragged
  from the queue onto a lane goes to that machine (if it prints the
  product and has a place), instead of the one it came with. The
  operator's pull still goes to the machine they are on (item 12).
- Pagamentos: each payment shows who tried to pay and what they were
  buying (the quote's customer and items, and its order if there is
  one); a click opens the customer's name, e-mail, CPF/CNPJ, WhatsApp
  and delivery, the quote, and Mercado Pago's id and status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-31 17:23:35 -03:00
parent a010b2507e
commit 388408d4d6
5 changed files with 170 additions and 31 deletions

View File

@@ -283,7 +283,31 @@ def payment_events(state: Literal['open','resolved','all'] = 'open',
ORDER BY received_at DESC,id DESC LIMIT %s OFFSET %s''', (limit, offset)).fetchall()
total = c.execute('''SELECT count(*) AS n FROM dtf_local.payment_events
WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') ''' + where).fetchone()['n']
return {'issues': rows, 'total': total}
for row in rows:
row.update(payment_context(c, row))
return {'issues': rows, 'total': total, 'thumbnails': thumbnails(c, [r['quote'] for r in rows if r.get('quote')])}
def payment_context(c, row):
"""Who tried to pay and for what: the quote the payment points to (its
customer, items and total), its order if there is one, the method of the
last attempt and Mercado Pago's own words about the payment."""
payload = c.execute('SELECT payload FROM dtf_local.payment_events WHERE id=%s', (row['id'],)).fetchone()['payload'] or {}
out = {'payment_id': payload.get('payment_id'), 'status_detail': payload.get('status_detail'), 'quote': None, 'order': None, 'method': None}
try:
quote_id = UUID(str(row.get('reference') or ''))
except ValueError:
return out
quote = c.execute('SELECT id,draft,approved,created_at,approved_at FROM dtf_local.quotes WHERE id=%s', (quote_id,)).fetchone()
if not quote:
return out
out['quote'] = {'id': quote['id'], 'draft': quote['draft'], 'created_at': quote['created_at'], 'approved_at': quote['approved_at'],
'total_cents': (quote['approved'] or {}).get('total_cents')}
out['order'] = c.execute('SELECT id,number,state,cancelled_at FROM dtf_local.orders WHERE quote_id=%s', (quote_id,)).fetchone()
attempt = c.execute('''SELECT method,status FROM dtf_local.payment_intents WHERE quote_id=%s
ORDER BY created_at DESC LIMIT 1''', (quote_id,)).fetchone()
out['method'] = attempt['method'] if attempt else None
return out
@router.get('/api/operator/events')
@@ -870,7 +894,22 @@ def move(uid: UUID, body: Move, request: Request, user=Depends(operator)):
raise HTTPException(409, 'Escolha a máquina em que você está.')
if not pulling and str(row['machine_id'] or '') != session_machine['id']:
raise HTTPException(403, 'Este pedido é de outra máquina: só quem está nela move o card.')
if pulling and session_machine and (account['role'] == 'operador' or not row['machine_chosen']):
# Dropped on a machine's lane in Imprimindo: that machine, when it
# prints the product. The operator's pull stays their machine's.
if pulling and body.machine_id:
if account['role'] == 'operador':
if str(body.machine_id) != session_machine['id']:
raise HTTPException(409, f"Você está na {session_machine['name']}: o que você puxa vai para ela.")
else:
target = c.execute('SELECT name, products, active FROM dtf_local.machines WHERE id=%s',
(body.machine_id,)).fetchone()
if not target or not target['active']:
raise HTTPException(409, 'Essa máquina não existe mais ou está desativada.')
if machines.product_family(row) not in target['products']:
raise HTTPException(409, f"A {target['name']} não imprime este produto.")
row['machine_id'] = body.machine_id
c.execute('UPDATE dtf_local.orders SET machine_id=%s, machine_chosen=true WHERE id=%s', (body.machine_id, uid))
if pulling and session_machine and not body.machine_id and (account['role'] == 'operador' or not row['machine_chosen']):
prints = c.execute('SELECT products FROM dtf_local.machines WHERE id=%s', (session_machine['id'],)).fetchone()
if machines.product_family(row) in (prints or {}).get('products', []):
row['machine_id'] = session_machine['id']

View File

@@ -264,6 +264,8 @@ class Move(StrictModel):
state: Literal['rec','tra','imp','cor','rev','fin']
version: int = Field(ge=0)
reason: str = Field(default='', max_length=1000)
# Pulled into Imprimindo onto a machine's lane: the machine it prints on.
machine_id: UUID | None = None
class Resolution(StrictModel):
note: str = Field(min_length=3, max_length=1000)

View File

@@ -399,7 +399,7 @@ def run():
cap = admin.call('/operator/machines', {'name': f'Cap {tag}', 'products': ['textil']})['id']
machines.append(cap)
with db.connect() as c:
pulled = [order_fixture(c, owner, 'file') for _ in range(4)]
pulled = [order_fixture(c, owner, 'file') for _ in range(5)]
made.extend(pulled)
for _, oid in pulled:
upload = uuid4()
@@ -410,7 +410,7 @@ def run():
VALUES(%s,%s,%s,0,'final','ok','t')''', (uuid4(), oid, upload))
c.execute("UPDATE dtf_local.orders SET state='tra', machine_id=%s, machine_chosen=true WHERE id=%s",
(cap, oid))
first, second_in, third, elsewhere = (str(oid) for _, oid in pulled)
first, second_in, third, elsewhere, lane = (str(oid) for _, oid in pulled)
pull = lambda oid, version=0: su.call(f'/operator/orders/{oid}/move', {'state': 'imp', 'version': version,
'reason': ''}, operator=True)
running = pull(first)
@@ -418,6 +418,14 @@ def run():
refused = su.call(f'/operator/orders/{third}/move', {'state': 'imp', 'version': 0, 'reason': ''},
operator=True, expected=409)
assert refused['detail'] == f'Cap {tag} já tem 2 em Imprimindo.', refused
# Dropped on another machine's lane, an order of the full one prints
# there instead; never on a machine that does not print its product.
not_uv = su.call(f'/operator/orders/{lane}/move', {'state': 'imp', 'version': 0, 'reason': '', 'machine_id': uv},
operator=True, expected=409)
assert not_uv['detail'] == f'A UV {tag} não imprime este produto.', not_uv
onto = su.call(f'/operator/orders/{lane}/move', {'state': 'imp', 'version': 0, 'reason': '', 'machine_id': textil2},
operator=True)
assert str(onto['machine_id']) == textil2 and onto['machine_chosen'], onto
loaded = su.call('/operator/board', operator=True)
board = {o['id']: o for o in loaded['orders']}
assert (board[first]['printing'], board[second_in]['printing'], board[third]['printing']) == \

View File

@@ -251,6 +251,10 @@ main{padding:0}
.card+.lanehead,.freeslot+.lanehead{margin-top:8px}
.freeslot{display:flex;align-items:center;justify-content:center;gap:9px;min-height:46px;padding:8px 14px;border:1.5px dashed var(--ln2);border-radius:11px;font-size:12.5px;color:var(--tx3);text-align:center}
.freemark{width:10px;height:10px;flex:none;border-radius:2px;border:1.5px dashed var(--ln3)}
/* Dragging into Imprimindo: the machine lane the card would drop on. */
.lanehead.droplane,.lanehead.droplane b{color:var(--acc)}
.freeslot.droplane{border-color:var(--acc);color:var(--acc);background:color-mix(in srgb,var(--acc) 6%,transparent)}
.card.droplane{border-color:color-mix(in srgb,var(--acc) 50%,transparent)}
.card{display:flex;flex-direction:column;gap:10px;width:100%;padding:10px;border:1px solid var(--ln);border-radius:11px;background:var(--sf);text-align:left;color:inherit;transition:border-color .15s,transform .25s cubic-bezier(.2,.8,.2,1),box-shadow .25s}
.card:hover{border-color:var(--ln3);transform:translateY(-1px);box-shadow:var(--lift)}
@@ -789,6 +793,20 @@ select.inp{appearance:none;-webkit-appearance:none;padding-right:32px;background
.mtile ul b{margin-left:auto;font-weight:600;color:var(--tx)}
.mtiles .emptystate{background:var(--sf)}
/* A payment's details: who, what for, what Mercado Pago said. */
.modal h4.sh{margin:4px 0 -8px;font-size:13px;font-weight:650;color:var(--tx2)}
.modal .prow{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
.paybox,.modal .mblock{display:flex;flex-direction:column;padding:4px 16px;border:1px solid var(--ln);border-radius:12px;background:var(--sf2)}
.paybox .mfact,.modal .mfact{display:flex;justify-content:space-between;gap:16px;padding:10px 0;border-bottom:1px solid var(--ln);font-size:13.5px}
.paybox .mfact:last-child{border-bottom:0}
.paybox .mfact span{color:var(--tx2);flex:none}
.paybox .mfact b{font-weight:550;text-align:right;min-width:0;overflow-wrap:anywhere;display:flex;align-items:center;justify-content:flex-end;gap:4px}
.modal .mlist{display:flex;flex-direction:column;border:1px solid var(--ln);border-radius:12px;overflow:hidden}
.modal .mli{display:flex;align-items:center;gap:12px;padding:10px 14px;border-bottom:1px solid var(--ln)}
.modal .mli:last-child{border-bottom:0}
.modal .mli .grow{flex:1;min-width:0}
#payments .table td .who{gap:10px}
/* Lists never change the page's size: a panel keeps its height and its
list scrolls inside, however many users, machines or orders there are. */
.scrollbox{overflow:auto;min-height:0}

View File

@@ -820,13 +820,15 @@ function renderBoard(){
// correction needs a reason, so those happen in the order panel.
column.ondragover=e=>{
if(dragging?.state===state&&state!=='fin'&&mayReorder(state)){e.preventDefault();markDrop(column,e.clientY);return;}
if(!column.classList.contains('allowed'))return;e.preventDefault();column.classList.add('target');};
column.ondragleave=e=>{if(!column.contains(e.relatedTarget)){column.classList.remove('target');clearDrop();}};
if(!column.classList.contains('allowed'))return;e.preventDefault();column.classList.add('target');
if(state==='imp')markLane(column,laneAt(column,e.clientY));};
column.ondragleave=e=>{if(!column.contains(e.relatedTarget)){column.classList.remove('target');markLane(column,null);clearDrop();}};
column.ondrop=async e=>{e.preventDefault();column.classList.remove('target');
const order=board.orders.find(o=>o.id===e.dataTransfer.getData('text/plain'));
const machine=state==='imp'?laneAt(column,e.clientY):null;markLane(column,null);
if(!order)return;
try{
if(order.state!==state)await move(order,state);
if(order.state!==state)await move(order,state,'',machine);
else if(state!=='fin')await reorder(order,column,e.clientY);
}catch(error){say(error.message,true);}
finally{clearDrop();}};
@@ -843,34 +845,46 @@ function renderBoard(){
for(const col of cols)col.classList.toggle('pick',col.dataset.state===phoneCol);
}
// Imprimindo, one lane per machine (app/machines.py): its name and places,
// the order printing, the one ripping, then a free place. Machines with
// nothing printing share one line, except the session's own, which keeps its
// lane so the operator sees the place waiting.
// the order printing, the one ripping, then its free place. Every active
// machine has its lane, so a card dragged from the queue can be dropped on
// the machine it goes to print on.
function printingLanes(orders){
const cap=board.printing_cap||2, mine=myMachine()?.id;
const filtered=Object.values(boardFilter).some(Boolean);
const out=[], free=[];
const list=(board.machines||[]).filter(m=>m.active||m.states?.imp||orders.some(o=>o.machine?.id===m.id));
const out=[];
const list=(board.machines||[]).filter(m=>m.active||orders.some(o=>o.machine?.id===m.id));
for(const m of list){
const here=orders.filter(o=>o.machine?.id===m.id)
.sort((a,b)=>(a.printing==='imprimindo'?0:1)-(b.printing==='imprimindo'?0:1));
// Filtered, a lane with nothing to show stays out; unfiltered, the places count every order.
const n=filtered?here.length:Math.max(m.states?.imp||0,here.length);
if(filtered&&!here.length)continue;
if(!filtered&&!n&&m.id!==mine){free.push(m.name);continue;}
const lane=node('div',undefined,'lanehead'+(m.id===mine?' mine':''));
const n=filtered?here.length:Math.max(m.states?.imp||0,here.length);
const lane=node('div',undefined,'lanehead'+(m.id===mine?' mine':''));lane.dataset.machine=m.id;
const load=n>cap?'acima do limite':n>=cap?'cheia':plural(cap-n,'vaga','vagas');
lane.append(svgIcon(IC.printer,'i s'),node('b',m.name),node('span',(m.id===mine?'sua máquina · ':'')+load));
lane.title=m.name+' · '+n+' de '+cap+(n>=cap?' · cheia: abre vaga quando um pedido sair de Imprimindo':'');
out.push(lane,...here.map(o=>card(o)));
if(!filtered)for(let i=n;i<cap;i++){const slot=node('div',undefined,'freeslot');slot.append(node('i',undefined,'freemark'),'Vaga livre na '+m.name);out.push(slot);}
out.push(lane,...here.map(o=>{const c=card(o);c.dataset.machine=m.id;return c;}));
if(!filtered&&n<cap){
const slot=node('div',undefined,'freeslot');slot.dataset.machine=m.id;
slot.append(node('i',undefined,'freemark'),cap-n>1?plural(cap-n,'vaga livre','vagas livres')+' na '+m.name:'Vaga livre na '+m.name);out.push(slot);
}
}
// An order whose machine is gone or off still shows.
const loose=orders.filter(o=>!list.some(m=>m.id===o.machine?.id));
if(loose.length){const lane=node('div',undefined,'lanehead');lane.append(svgIcon(IC.printer,'i s'),node('b','Sem máquina'));out.push(lane,...loose.map(o=>card(o)));}
if(free.length){const line=node('div',undefined,'freeslot');line.append(node('i',undefined,'freemark'),'Livres: '+free.join(' · '));out.push(line);}
return out;
}
// The machine lane under the pointer in Imprimindo: the last lane head above it.
function laneAt(column,y){
let found=null;
for(const el of column.querySelectorAll('[data-machine]')){
if(el.getBoundingClientRect().top<=y)found=el.dataset.machine;
}
return found||column.querySelector('.lanehead[data-machine]')?.dataset.machine||null;
}
function markLane(column,id){
for(const l of column.querySelectorAll('.lanehead,.freeslot,.card'))l.classList.toggle('droplane',!!id&&l.dataset.machine===id);
}
// A card's place in the print queue, among the orders of its product (a
// textile machine pulls the next textile order).
const uvOrder=o=>o.snapshot.items.some(i=>i.mode.startsWith('uv'));
@@ -1039,8 +1053,8 @@ async function loadOlderFinished(){
const fresh=page.orders.filter(o=>!known.has(o.id));
olderFinished.push(...fresh);board.orders.push(...fresh);finishedMore=page.has_more;renderBoard();
}
async function move(order,state,reason=''){
await api('/orders/'+order.id+'/move',{state,version:order.version,reason});
async function move(order,state,reason='',machine=null){
await api('/orders/'+order.id+'/move',{state,version:order.version,reason,...(machine?{machine_id:machine}:{})});
await load();
}
@@ -2690,7 +2704,7 @@ function moreButton(container,has,fn){
let issueState='open', issueRows=[], issueTotal=0, issuePage=1, issueSize=20, issueLoading=0;
async function loadIssues(){
const token=++issueLoading;
const page=await api('/payment-events?'+new URLSearchParams({state:issueState,limit:String(issueSize),offset:String((issuePage-1)*issueSize)}));
const page=absorb(await api('/payment-events?'+new URLSearchParams({state:issueState,limit:String(issueSize),offset:String((issuePage-1)*issueSize)})));
if(token!==issueLoading)return;
issueRows=page.issues;issueTotal=page.total;
if(issuePage>1&&!issueRows.length&&issueTotal){issuePage=Math.ceil(issueTotal/issueSize);return loadIssues();}
@@ -2713,10 +2727,12 @@ function renderIssues(){
if(PHONE.matches){
$('payments').replaceChildren(tools,...issueRows.map(issue=>{
const card=node('div',undefined,'mblock pcard'),refused=issue.outcome.startsWith('refused');
const top=node('div',undefined,'prow');top.append(issue.resolved_at?statePill('Resolvido','ok'):statePill(refused?'Recusado':'Atenção',refused?'bad':'warn'),node('span',when(issue.received_at),'lbl right'));
const top=node('div',undefined,'prow');top.append(issueKind(issue),node('span',when(issue.received_at),'lbl right'));
const mid=node('div',undefined,'prow base');
mid.append(node('b',issue.reference?'Cotação '+String(issue.reference).slice(0,8):'Sem cotação','grow'),node('b',issue.amount_cents==null?'Sem valor':money(issue.amount_cents)));
card.append(top,mid,node('span',issue.provider+', evento '+issue.event_id,'sub'),node('p',outcomeText(issue.outcome),'nnote'));
const who=paymentWho(issue);
mid.append(node('b',who.title,'grow'),node('b',issue.amount_cents==null?'Sem valor':money(issue.amount_cents)));
card.append(top,mid,node('span',[who.mail,issue.quote?productLine(issue.quote.draft.items):''].filter(Boolean).join(', ')||'Sem cotação ligada','sub'),node('p',outcomeText(issue.outcome),'nnote'));
card.onclick=e=>{if(!e.target.closest('button'))paymentDialog(issue);};
if(issue.resolved_at)card.append(node('span','Por '+issue.resolved_by+' em '+when(issue.resolved_at)+': '+issue.resolution,'sub'));
else if(may('manage'))card.append(button('Registrar resolução',async()=>resolveDialog(issue),'btn wide'));
return card;}),pager({page:issuePage,size:issueSize,total:issueTotal,noun:'pagamentos',compact:true,fixedSize:true,
@@ -2724,21 +2740,28 @@ function renderIssues(){
return;
}
const table=node('table',undefined,'table');
const head=node('tr');for(const [t,c] of [['Quando'],['O que aconteceu'],['Referência'],['Valor pago','r'],['']]){const th=node('th',t,c);th.scope='col';head.append(th);}
const head=node('tr');for(const [t,c] of [['Quando'],['Cliente'],['O que aconteceu'],['O que estava comprando'],['Valor pago','r'],['']]){const th=node('th',t,c);th.scope='col';head.append(th);}
const thead=node('thead');thead.append(head);const tbody=node('tbody');
for(const issue of issueRows){
const tr=node('tr');
const refused=issue.outcome.startsWith('refused');
const kind=issue.resolved_at?statePill('Resolvido','ok'):statePill(refused?'Recusado':'Atenção',refused?'bad':'warn');
const what=node('td');what.append(kind,node('span',outcomeText(issue.outcome),'sub'));
const tr=node('tr',undefined,'click');tr.onclick=()=>paymentDialog(issue);
const who=paymentWho(issue);
const client=node('td');client.append(node('b',who.title),node('span',who.mail||(issue.quote?'':'Sem cotação ligada'),'sub'));
const what=node('td');what.append(issueKind(issue),node('span',outcomeText(issue.outcome),'sub'));
if(issue.resolved_at)what.append(node('span','Por '+issue.resolved_by+' em '+when(issue.resolved_at)+': '+issue.resolution,'sub'));
const ref=node('td');ref.append(node('span',issue.reference?'Cotação '+String(issue.reference).slice(0,8):'Sem cotação','code'),node('span',issue.provider+', evento '+issue.event_id,'sub'));
const buying=node('td');
if(issue.quote){const items=issue.quote.draft.items;
const line=node('span',undefined,'who');line.append(artBox(items,'qthumb rart'),node('span',productLine(items)+', '+metres(items.reduce((t,i)=>t+Number(i.billed_metres||i.metres),0))));
buying.append(line);
if(issue.order)buying.append(node('span','Pedido #'+issue.order.number,'sub'));}
else buying.append(node('span',issue.reference?'Referência '+String(issue.reference).slice(0,12):'Sem referência','sub'));
const paid=node('td',undefined,'r nowrap');paid.append(node('b',issue.amount_cents==null?'Sem valor':money(issue.amount_cents)));
if(issue.quote?.total_cents)paid.append(node('span','cotação '+money(issue.quote.total_cents),'sub'));
const act=node('td',undefined,'r');
if(!issue.resolved_at){
if(may('manage'))act.append(button('Registrar resolução',async()=>resolveDialog(issue),'btn'));
else act.append(node('span','Aguarda a Gestão','lbl'));
}
tr.append(node('td',when(issue.received_at),'nowrap muted'),what,ref,node('td',issue.amount_cents==null?'Sem valor':money(issue.amount_cents),'r nowrap strong'),act);
tr.append(node('td',when(issue.received_at),'nowrap muted'),client,what,buying,paid,act);
tbody.append(tr);
}
table.append(thead,tbody);
@@ -2748,6 +2771,55 @@ function renderIssues(){
onSize:n=>{issueSize=n;issuePage=1;loadIssues().catch(e=>say(e.message,true));}}));
$('payments').replaceChildren(tools,panel);
}
// Who tried to pay: the quote's customer, as on the board.
function paymentWho(issue){
if(!issue.quote)return {title:'Cliente não identificado',mail:''};
return buyer(issue.quote.draft);
}
function issueKind(issue){
const refused=issue.outcome.startsWith('refused');
return issue.resolved_at?statePill('Resolvido','ok'):statePill(refused?'Recusado':'Atenção',refused?'bad':'warn');
}
const METHODS={pix:'Pix',card:'Cartão',debit:'Débito'};
// Mercado Pago's words about a payment, in ours; anything else as it came.
const MP_DETAIL={accredited:'Creditado',refunded:'Estornado',partially_refunded:'Estornado em parte',by_collector:'Estornado pela loja',
by_payer:'Contestado pelo cliente',pending_waiting_transfer:'Aguardando o Pix',pending_waiting_payment:'Aguardando o pagamento',
pending_contingency:'Em análise',pending_review_manual:'Em análise manual',expired:'Expirado',
cc_rejected_insufficient_amount:'Cartão sem limite',cc_rejected_bad_filled_security_code:'Código de segurança errado',
cc_rejected_call_for_authorize:'O banco pediu autorização',cc_rejected_other_reason:'Recusado pelo banco'};
// Everything about a payment that needed a person: who, what they were
// buying, what Mercado Pago said, and the order it became, if any.
function paymentDialog(issue){
const body=[],q=issue.quote;
const rows=(pairs)=>{const box=node('div',undefined,'mblock mfacts paybox');
for(const [k,v] of pairs){if(v===null||v===undefined||v==='')continue;const r=node('div',undefined,'mfact');const b=node('b');b.append(v);r.append(node('span',k),b);box.append(r);}
return box;};
const what=node('div',undefined,'prow');what.append(issueKind(issue),node('span',outcomeText(issue.outcome),'nnote'));body.push(what);
if(q){
const c=q.draft.customer||{},dest=q.draft.destination,who=buyer(q.draft);
const doc=node('span',undefined,'factline');doc.append(cnpj(c.cnpj),copyButton(cnpj(c.cnpj),'Copiar '+docKind(c.cnpj)));
const zap=whatsappLink(c.zap);let phone=c.zap||'';
if(zap){phone=node('a',c.zap);phone.href=zap;phone.target='_blank';phone.rel='noopener noreferrer';}
body.push(node('h4','Cliente','sh'),rows([['Nome',who.title],['E-mail',c.mail],[docKind(c.cnpj),doc],['WhatsApp',phone],
['Entrega',dest?dest.recipient+', '+dest.street+', '+dest.number+', '+dest.city+'/'+dest.state+', CEP '+dest.postal_code:'Retirada em Franca']]));
const items=q.draft.items;
const list=node('div',undefined,'mlist');
items.forEach(i=>{const r=node('div',undefined,'mli');r.append(artBox([i],'qthumb rart'),node('span',PRODUCT[i.mode],'grow'),node('b',metres(i.billed_metres||i.metres)));list.append(r);});
body.push(node('h4','O que estava comprando','sh'),list,rows([['Cotação',node('span',String(q.id).slice(0,8),'code')],['Feita em',when(q.created_at)],
['Aprovada em',q.approved_at?when(q.approved_at):'ainda não aprovada'],['Total da cotação',q.total_cents!=null?money(q.total_cents):'']]));
}else body.push(node('p','O pagamento não aponta para uma cotação conhecida: confira pelo id no Mercado Pago.','nnote'));
body.push(node('h4','Pagamento','sh'),rows([['Valor pago',issue.amount_cents==null?'Sem valor':money(issue.amount_cents)],
['Forma',METHODS[issue.method]||''],['Mercado Pago',issue.payment_id?node('span',issue.payment_id,'code'):''],
['Situação no Mercado Pago',MP_DETAIL[issue.status_detail]||issue.status_detail||''],['Recebido em',when(issue.received_at)],
['Resolvido',issue.resolved_at?issue.resolved_by+' em '+when(issue.resolved_at)+': '+issue.resolution:'']]));
const foot=[];
if(issue.order){const open=node('button','Abrir pedido #'+issue.order.number,'btn');open.type='button';
open.onclick=()=>{m.close();const known=board.orders.find(o=>o.id===issue.order.id);showTab('board');if(known)openPanel(known.id);else say('O pedido #'+issue.order.number+' não está no quadro agora: busque pelo número.');};foot.push(open);}
if(!issue.resolved_at&&may('manage')){const r=node('button','Registrar resolução','btn pri right');r.type='button';r.onclick=()=>{m.close();resolveDialog(issue);};foot.push(r);}
else{const close=node('button','Fechar','btn ghost right');close.type='button';close.onclick=()=>m.close();foot.push(close);}
const who=paymentWho(issue);
const m=modal(who.title,{text:(issue.amount_cents==null?'Pagamento sem valor':'Pagamento de '+money(issue.amount_cents))+', '+when(issue.received_at),body,foot,width:600});
}
function resolveDialog(issue){
const note=node('textarea');note.placeholder='Ex.: estornado no Mercado Pago, cliente avisado';note.setAttribute('aria-label','Resolução');
note.required=true;note.minLength=3;note.maxLength=1000;