PageSourceSearch

https://sentinel-365-c9d4f.web.app/assets/ViagensList-29a9Lw-i.js

js sentinel-365-c9d4f.web.app collected 2026-10-03 12:38:03 UTC 31,782 bytes, 1 lines download raw bytes

1import{j as e,r as g,b as re,u as ie}from"./react-vendor-pafHdoJx.js";import{c as le,b as $,d as b,u as q,l as X,w as ne,C as ce}from"./index-Db0fDLGN.js";import{E as z}from"./ErrorState-B9i6eo2M.js";import{E as de}from"./EntityList-DHyuL9ql.js";import{a as Z}from"./ComplianceBadges-B6KO2l0w.js";import{c as me}from"./trip-urgency-DbS8HR5U.js";import{O as ue}from"./ObjectDrawer-DyT69DrE.js";import{aK as K,d5 as pe,l as J,ae as Q,r as xe,d6 as fe,aE as ge,L as Y,D as ve,d7 as he,v as be,M as ye,X as je,Z as Ne}from"./ui-vendor-DLXJn6s3.js";import{A as ke}from"./AdaInline-Ct5kRNHe.js";import{C as Ce}from"./Comments-C_vFA2mA.js";import{A as we}from"./ActivityFeed-DAmzN5j6.js";import{P as Ae}from"./PodPanel-DWX7p1mt.js";import"./map-vendor-Dr8zbd0c.js";import"./firebase-vendor-D3UzkAhn.js";const Se={critical:{label:"Crítica",bg:"#fef2f2",fg:"#b91c1c",dot:"#dc2626"},warning:{label:"Atenção",bg:"#fff7ed",fg:"#9a3412",dot:"#ea580c"},monitor:{label:"Monitorar",bg:"#fefce8",fg:"#854d0e",dot:"#ca8a04"},ok:{label:"OK",bg:"transparent",fg:"var(--page-text-muted, #94a3b8)",dot:"var(--page-text-muted, #94a3b8)"}};function De({urgency:s,hideOk:r=!0,showScore:u=!1,className:l}){if(r&&s.tier==="ok")return null;const n=Se[s.tier],m=s.topReasons.length>0?s.topReasons.join(" · "):`Score ${s.score}`;return e.jsxs("span",{role:"status","aria-label":`Urgência ${n.label}: ${m}`,title:m,"data-testid":"urgency-badge","data-tier":s.tier,className:le("inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[10px] font-semibold",l),style:{background:n.bg,color:n.fg},children:[e.jsx("span",{"aria-hidden":"true",className:"inline-block h-1.5 w-1.5 rounded-full",style:{background:n.dot}}),n.label,u&&e.jsxs("span",{className:"opacity-70","data-testid":"urgency-score",children:["(",s.score,")"]})]})}const P={com_defesa:{rotulo:"Com defesa",cor:"#059669",Icone:Q,ajuda:"Todas as peças exigíveis desta viagem estão provadas e guardadas."},faltando_peca:{rotulo:"Faltando peça",cor:"#DC2626",Icone:J,ajuda:"Esta viagem encerrou sem alguma prova que era exigível."},em_andamento:{rotulo:"Em andamento",cor:"#64748B",Icone:pe,ajuda:"A defesa fecha quando o manifesto encerra."},sem_lastro:{rotulo:"Sem lastro",cor:"#D97706",Icone:K,ajuda:"Faltam cadastros para julgar esta viagem — não é irregularidade, é ausência de base."}};function $e({estado:s,faltando:r,compacto:u=!1}){const l=P[s]??P.em_andamento,n=s==="faltando_peca"?r??0:0;return e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-semibold whitespace-nowrap",style:{background:`${l.cor}18`,color:l.cor},title:l.ajuda,children:[e.jsx(l.Icone,{className:"w-3 h-3 shrink-0","aria-hidden":"true"}),u?l.rotulo:n>0?`${l.rotulo}${n>1?` · ${n}`:""}`:l.rotulo]})}function Fe(s){return(P[s]??P.em_andamento).ajuda}const Ee={regulatorio:"ANTT",trabalhista:"Trabalhista",fiscal:"Fiscal",patrimonial:"Carga e seguro",contratual:"Contratual",dados:"LGPD"},ee={provada:{cor:"#059669",Icone:Q},faltando:{cor:"#DC2626",Icone:J},sem_lastro:{cor:"#D97706",Icone:K},nao_aplicavel:{cor:"var(--page-text-muted)",Icone:fe}};function Le(s){return s?new Date(s).toLocaleDateString("pt-BR"):""}function T({p:s}){const r=ee[s.estado]??ee.nao_aplicavel;return e.jsxs("li",{className:"flex items-start gap-2.5 py-2",style:{borderTop:"1px solid var(--border-primary)"},children:[e.jsx(r.Icone,{className:"w-4 h-4 shrink-0 mt-0.5",style:{color:r.cor},"aria-hidden":"true"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm",style:{color:"var(--page-text)"},children:s.rotulo}),e.jsxs("p",{className:"text-[11px]",style:{color:"var(--page-text-muted)"},children:[Ee[s.dominio]||s.dominio,s.detalhe?` · ${s.detalhe}`:"",s.emMs?` · ${Le(s.emMs)}`:""]})]})]})}function _e({chave:s}){const{data:r,loading:u,error:l,refetch:n}=$(()=>b.dossieDaViagem(s),[s]),[m,d]=g.useState(!1);if(u&&!r)return e.jsx("p",{className:"text-sm",style:{color:"var(--page-text-muted)"},children:"Montando o dossiê…"});if(l&&/não montado|404/i.test(String(l)))return e.jsxs("div",{className:"rounded-xl p-4",style:{background:"var(--surface-secondary)",border:"1px solid var(--border-primary)"},children:[e.jsx("p",{className:"text-sm font-semibold",style:{color:"var(--page-text)"},children:"A defesa ainda não fechou"}),e.jsx("p",{className:"text-xs mt-1",style:{color:"var(--page-text-muted)"},children:"O dossiê é montado na varredura seguinte ao encerramento do manifesto."})]});if(l)return e.jsx(z,{error:l,onRetry:n,title:"Não consegui carregar a defesa"});if(!r)return null;const c=r.pecas||[],t=c.filter(p=>p.estado==="faltando"),f=c.filter(p=>p.estado==="sem_lastro"),y=c.filter(p=>p.estado==="provada"),h=c.filter(p=>p.estado==="nao_aplicavel"),N=r.estado;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl p-4",style:{background:"var(--surface-secondary)",border:"1px solid var(--border-primary)"},children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx($e,{estado:N,faltando:t.length}),r.cobertura!=null&&e.jsxs("span",{className:"text-sm font-semibold tabular-nums",style:{color:"var(--page-text)"},children:[Math.round(r.cobertura*100),"% das peças provadas"]})]}),e.jsxs("p",{className:"text-xs mt-1.5",style:{color:"var(--page-text-muted)"},children:[Fe(N)," Base: ",r.provadas," de ",r.aplicaveis," peças exigíveis nesta viagem."]})]}),t.length>0&&e.jsxs("section",{"aria-labelledby":"defesa-falta",children:[e.jsx("h4",{id:"defesa-falta",className:"text-xs font-semibold uppercase tracking-wide mb-1",style:{color:"#DC2626"},children:"O que falta"}),e.jsx("ul",{children:t.map(p=>e.jsx(T,{p},p.id))})]}),f.length>0&&e.jsxs("section",{"aria-labelledby":"defesa-lastro",children:[e.jsx("h4",{id:"defesa-lastro",className:"text-xs font-semibold uppercase tracking-wide mb-1",style:{color:"#D97706"},children:"Sem base para afirmar"}),e.jsx("p",{className:"text-[11px] mb-1",style:{color:"var(--page-text-muted)"}
1,children:"Não é irregularidade — é cadastro que falta para julgar."}),e.jsx("ul",{children:f.map(p=>e.jsx(T,{p},p.id))})]}),(y.length>0||h.length>0)&&e.jsxs("section",{children:[e.jsxs("button",{type:"button",onClick:()=>d(p=>!p),"aria-expanded":m,className:"inline-flex items-center gap-1.5 text-xs font-medium",style:{color:"var(--page-text-secondary)"},children:[e.jsx(xe,{className:`w-3.5 h-3.5 transition-transform ${m?"rotate-180":""}`,"aria-hidden":"true"}),m?"Ocultar":"Ver"," as ",y.length," peças provadas",h.length>0?` e ${h.length} não aplicáveis`:""]}),m&&e.jsxs("ul",{className:"mt-1",children:[y.map(p=>e.jsx(T,{p},p.id)),h.map(p=>e.jsx(T,{p},p.id))]})]})]})}const R={verde:"#10B981",vermelho:"#EF4444",amarelo:"#F59E0B",cinza:"#9CA3AF"},oe={verde:Q,vermelho:ge,amarelo:J,cinza:K};function ae({c:s}){const r=oe[s.estado];return e.jsxs("div",{className:"flex items-start gap-2 py-1.5",style:{borderBottom:"1px solid var(--border-primary)"},children:[e.jsx(r,{className:"w-4 h-4 shrink-0 mt-0.5",style:{color:R[s.estado]},"aria-label":s.estado}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm",style:{color:"var(--page-text)"},children:s.label}),e.jsxs("p",{className:"text-xs",style:{color:"var(--page-text-muted)"},children:[s.detalhe,s.base?` · ${s.base}`:""]})]})]})}function Be({dispatchId:s,driverId:r,vehiclePlaca:u,chaveMdfe:l,gateApproved:n,gateLiberacao:m,onMudou:d}){const{toast:c}=q(),[t,f]=g.useState(!1),[y,h]=g.useState(null),[N,p]=g.useState(null),[A,L]=g.useState(""),[I,F]=g.useState(!1),[U,G]=g.useState(null),{data:_,loading:j}=$(()=>l?b.ponteGate(l):Promise.resolve(null),[l]),B=((_==null?void 0:_.condicoes)||[]).map(i=>({id:`mdfe:${i.id}`,label:i.label,base:i.base,detalhe:i.detalhe,grupo:"manifesto",estado:i.estado==="verde"?"verde":i.estado==="vermelho"?"vermelho":"cinza"})),W=async()=>{if(!t){f(!0);try{const i=await b.safetyGatePreTrip({driverId:r||void 0,vehiclePlaca:u||void 0,dispatchId:s}),E=(i.checks||[]).map((D,V)=>({id:`pt:${V}`,label:`${D.category} · ${D.item}`,detalhe:D.detail,grupo:"motorista_veiculo",estado:D.status==="ok"?"verde":D.status==="blocked"?"vermelho":"amarelo"}));h(E),p(i.result||null),X("semaforo_rodou",{resultado:i.result,dispatchId:s}),d==null||d()}catch(i){c({kind:"error",title:"Não deu para verificar agora",description:i==null?void 0:i.message})}finally{f(!1)}}},M=async()=>{if(!(I||A.trim().length<10)){F(!0);try{const i=await b.dispatchGateLiberar(s,A.trim());G(i.gateLiberacao),L(""),c({kind:"success",title:"Partida liberada com exceção",description:"A justificativa ficou no registro."}),X("semaforo_liberou_excecao",{dispatchId:s}),d==null||d()}catch(i){c({kind:"error",title:"Não deu para liberar",description:i==null?void 0:i.message})}finally{F(!1)}}},a=U||m||null,o=[...y||[],...B],x=o.filter(i=>i.estado==="vermelho").length,k=o.filter(i=>i.estado==="cinza").length,C=o.length-k,v=a?{tom:"amarelo",texto:`Liberada com exceção por ${a.nome||"gestão"}`}:x>0?{tom:"vermelho",texto:`${x} condição${x>1?"ões":""} em vermelho — segura`}:N==="approved"||N==="warning"||n?{tom:"verde",texto:"Pode sair"}:{tom:"cinza",texto:"Motorista e veículo ainda não verificados"},S=oe[v.tom];return e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"rounded-lg px-3 py-2.5 flex items-center gap-2",style:{background:`${R[v.tom]}14`,border:`1px solid ${R[v.tom]}40`},children:[e.jsx(S,{className:"w-5 h-5 shrink-0",style:{color:R[v.tom]},"aria-hidden":"true"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold",style:{color:"var(--page-text)"},children:v.texto}),e.jsxs("p",{className:"text-xs",style:{color:"var(--page-text-muted)"},children:[o.length?`${C} de ${o.length} condições verificadas`:"nenhuma condição verificada ainda",k?` · ${k} sem fonte conectada`:""]})]})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide",style:{color:"var(--page-text-muted)"},children:"Motorista e veículo"}),e.jsxs("button",{type:"button",onClick:W,disabled:t||!r&&!u,className:"inline-flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-md disabled:opacity-50",style:{background:"#F97316",color:"#fff"},children:[t?e.jsx(Y,{className:"w-3 h-3 animate-spin"}):e.jsx(ve,{className:"w-3 h-3"}),y?"Verificar de novo":"Verificar agora"]})]}),!r&&!u?e.jsx("p",{className:"text-xs",style:{color:"var(--page-text-muted)"},children:"Sem motorista nem veículo no despacho — não há o que verificar."}):y?y.map(i=>e.jsx(ae,{c:i},i.id)):e.jsx("p",{className:"text-xs",style:{color:"var(--page-text-muted)"},children:n?"Verificação anterior aprovada. Rode de novo para ver o detalhe atual.":"Consulta vínculo, CNH, SENATRAN e as três apólices. Não roda sozinha porque consulta serviços externos."})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide mb-1",style:{color:"var(--page-text-muted)"},children:"O manifesto"}),l?j&&!_?e.jsx("p",{className:"text-xs",style:{color:"var(--page-text-muted)"},children:"Lendo o manifesto…"}):B.length?B.map(i=>e.jsx(ae,{c:i},i.id)):e.jsx("p",{className:"text-xs",style:{color:"var(--page-text-muted)"},children:"O manifesto não pôde ser lido agora."}):e.jsx("p",{className:"text-xs",style:{color:"var(--page-text-muted)"},children:"Despacho sem MDF-e vinculado — averbação, CIOT, vale-pedágio e capacidade só são verificáveis pelo manifesto."})]}),!a&&x>0&&e.jsxs("section",{className:"rounded-lg p-3",style:{background:"rgba(245,158,11,0.08)",border:"1px solid rgba(245,158,11,0.35)"},children:[e.jsx("p",{className:"text-xs font-semibold mb-1",style:{color:"#D97706"}
1,children:"Liberar com exceção"}),e.jsx("p",{className:"text-xs mb-2",style:{color:"var(--page-text-muted)"},children:"A justificativa é o registro de quem assumiu o risco. Fica no histórico do despacho."}),e.jsx("textarea",{value:A,onChange:i=>L(i.target.value),rows:2,placeholder:"Por que esta viagem sai mesmo assim? (mínimo 10 caracteres)",className:"w-full rounded-md px-2 py-1.5 text-sm",style:{background:"var(--surface-primary)",border:"1px solid var(--border-primary)",color:"var(--page-text)"}}),e.jsxs("button",{type:"button",onClick:M,disabled:I||A.trim().length<10,className:"mt-2 inline-flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-md disabled:opacity-50",style:{background:"rgba(245,158,11,0.15)",color:"#D97706",border:"1px solid rgba(245,158,11,0.4)"},children:[I?e.jsx(Y,{className:"w-3 h-3 animate-spin"}):e.jsx(he,{className:"w-3 h-3"}),"Liberar a partida"]})]}),(a==null?void 0:a.justificativa)&&e.jsxs("p",{className:"text-xs",style:{color:"var(--page-text-muted)"},children:["Justificativa registrada: “",a.justificativa,"”"]})]})}function H(s){if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"){const r=Date.parse(s);return Number.isFinite(r)?r:null}return null}const te={aguardando:{label:"Aguardando",color:"#9CA3AF"},em_rota:{label:"Em rota",color:"#3B82F6"},concluida:{label:"Concluída",color:"#10B981"},cancelada:{label:"Cancelada",color:"#EF4444"},pending:{label:"Aguardando",color:"#9CA3AF"},accepted:{label:"Aceita",color:"#3B82F6"},loading:{label:"Carregando",color:"#8B5CF6"},in_transit:{label:"Em rota",color:"#3B82F6"},delivered:{label:"Entregue",color:"#10B981"},rejected:{label:"Recusada",color:"#EF4444"},cancelled:{label:"Cancelada",color:"#EF4444"}};function Ie(){const{toast:s}=q(),{data:r,refetch:u}=$(()=>b.dispatchAutoConfig(),[]),l=(r==null?void 0:r.ativo)===!0,[n,m]=g.useState(!1),d=async()=>{m(!0);try{await b.dispatchAutoConfigSet(!l),s({kind:"success",title:l?"Auto-despacho desligado.":"Auto-despacho ligado: MDF-e autorizado vira despacho e convida o motorista."}),u()}catch(c){s({kind:"error",title:(c==null?void 0:c.message)||"Não foi possível alterar"})}finally{m(!1)}};return e.jsxs("button",{onClick:d,disabled:n,className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-semibold border transition-colors",style:{borderColor:l?"#10B98140":"var(--border-primary)",background:l?"#10B98115":"transparent",color:l?"#10B981":"var(--page-text-secondary)"},title:"MDF-e autorizado (certificado A1) vira despacho automaticamente e convida o motorista por WhatsApp",children:[e.jsx(Ne,{size:13}),l?"Auto-despacho por MDF-e: ligado":"Ligar auto-despacho por MDF-e"]})}const Me=["todas","hoje","em_rota","sem_motorista","doc_pendente","urgencia"];function se(s){return s?s==="pra_criar"?"sem_motorista":Me.includes(s)?s:"todas":"todas"}const Ve=new Set(["em_rota","in_transit","em_transito"]);function sa({onNova:s}){var M;const{data:r,loading:u,error:l,refetch:n}=$(()=>b.dispatches(),[]),[m]=re(),[d,c]=g.useState(()=>se(m.get("filter"))),[t,f]=g.useState(null),y=ie(),{toast:h}=q(),[N,p]=g.useState(null),[A,L]=g.useState(null),[I,F]=g.useState(!1);async function U(a,o){F(!0);const x=await Promise.allSettled(a.map(v=>b.cancelDispatch(v.id,o)));F(!1),p(null);const k=x.filter(v=>v.status==="fulfilled").length,C=x.length-k;k&&h({kind:"success",title:k===1?`Viagem ${a[0].numero} cancelada.`:`${k} viagens canceladas.`}),C&&h({kind:"error",title:`${C} não ${C===1?"pôde":"puderam"} ser cancelada${C===1?"":"s"} — veja o status de cada uma.`}),n()}async function G(a){try{const o=await b.arriveDispatch(a.id);h({kind:"success",title:o!=null&&o.alreadyArrived?`Viagem ${a.numero} já estava concluída.`:`Viagem ${a.numero} concluída.`}),n()}catch(o){h({kind:"error",title:(o==null?void 0:o.message)||"Não foi possível concluir a viagem."})}finally{L(null)}}async function _(a){const o=a.filter(x=>x.driverId);if(o.length===0){h({kind:"warning",title:"Nenhuma das viagens selecionadas tem motorista designado."});return}F(!0);try{const x=await b.drivers(),k=Array.isArray(x)?x:(x==null?void 0:x.items)||(x==null?void 0:x.drivers)||[],C=new Map;for(const i of k)i!=null&&i.id&&(i.phone||i.telefone)&&C.set(i.id,i.phone||i.telefone);let v=0,S=0;for(const i of o){const E=C.get(i.driverId);if(!E){S++;continue}const D=`Olá ${i.motorista}! Sobre a viagem ${i.numero} (${i.cliente}), saída ${O(i.saida)||"a confirmar"}
1. Qualquer dúvida, responda por aqui.`;try{await b.waSendDirect(E,D,{refType:"dispatch",refId:i.id}),v++}catch{S++}}v&&h({kind:"success",title:`${v} mensagem${v===1?"":"s"} enfileirada${v===1?"":"s"} no WhatsApp.`}),S&&h({kind:"warning",title:`${S} motorista${S===1?"":"s"} sem telefone cadastrado ou com falha no envio.`})}catch(x){h({kind:"error",title:(x==null?void 0:x.message)||"Falha ao enviar pelo WhatsApp."})}finally{F(!1)}}g.useEffect(()=>{m.get("filter")&&c(se(m.get("filter")))},[m]);const j=g.useMemo(()=>((r==null?void 0:r.items)||(r==null?void 0:r.dispatches)||[]).map(o=>{var v,S,i,E,D,V;const x=o.status||"aguardando",k=parseFloat(o.valorFrete||o.freightValue||0)||0,C=me({id:o.id,status:x,estimatedDelivery:o.estimatedDelivery||o.etaDestino||o.deliveryDeadline||null,actualDelivery:o.actualDelivery||o.deliveredAt||null,lastSeenAt:H(o.lastSeenAt||o.lastPositionAt),valor:k,isVipClient:!!(o.isVipClient||(v=o.client)!=null&&v.vip),ciotExpiresAt:H(((S=o.ciot)==null?void 0:S.expiresAt)||o.ciotExpiresAt),mdfeExpiresAt:H(o.mdfeExpiresAt),hasSinistro:!!(o.hasSinistro||o.sinistroId)});return{id:o.id,numero:o.numero||((i=o.id)==null?void 0:i.slice(0,8))||"—",status:x,cliente:o.clienteOrigemNome||o.clienteNome||o.clientName||"—",motorista:o.driverName||o.motorista||"—",veiculo:o.vehiclePlate||((E=o.veiculo)==null?void 0:E.placa)||"—",saida:o.scheduledDate||o.departureDate||"",valor:k,cteStatus:o.cteChave?"ok":"warn",mdfeStatus:o.mdfeChave||o.chaveMdfe?"ok":"warn",ciotStatus:(D=o.ciot)!=null&&D.numero||o.ciotNumero?"ok":"warn",pefStatus:o.pefUrl?"ok":"unknown",urgency:C,origem:o.origem||null,aguardandoAceite:o.status==="pending"&&o.origem==="mdfe"&&!o.driverId,chaveMdfe:o.chaveMdfe||null,rotogramaId:o.rotogramaId||null,driverId:o.driverId||null,vehiclePlate:o.vehiclePlate||((V=o.veiculo)==null?void 0:V.placa)||null,gateApproved:o.gateApproved===!0,gateLiberacao:o.gateLiberacao||null}}),[r]),B=g.useMemo(()=>{if(d==="todas")return j;if(d==="hoje"){const a=new Date().toISOString().slice(0,10);return j.filter(o=>o.saida.slice(0,10)===a)}return d==="em_rota"?j.filter(a=>Ve.has(a.status)):d==="sem_motorista"?j.filter(a=>a.motorista==="—"):d==="doc_pendente"?j.filter(a=>a.cteStatus!=="ok"||a.mdfeStatus!=="ok"||a.ciotStatus!=="ok"):d==="urgencia"?j.filter(a=>a.urgency.tier!=="ok").sort((a,o)=>o.urgency.score-a.urgency.score):j},[j,d]),W=[{key:"numero",label:"VG",width:80,render:a=>e.jsx("span",{className:"font-mono",children:a.numero}),sortValue:a=>a.numero},{key:"status",label:"Status",width:120,render:a=>{const o=a.aguardandoAceite?{label:"Aguard. aceite",color:"#F59E0B"}:te[a.status]||{label:a.status,color:"#9CA3AF"};return e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:o.color}}),o.label]})},sortValue:a=>a.status},{key:"urgencia",label:"Urgência",width:110,render:a=>e.jsx(De,{urgency:a.urgency}),sortValue:a=>a.urgency.score},{key:"cliente",label:"Cliente",width:"1.2fr",render:a=>e.jsx("span",{children:a.cliente}),sortValue:a=>a.cliente},{key:"motorista",label:"Motorista",width:"1fr",render:a=>e.jsx("span",{children:a.motorista}),sortValue:a=>a.motorista},{key:"veiculo",label:"Veículo",width:100,render:a=>e.jsx("span",{className:"font-mono",children:a.veiculo})},{key:"saida",label:"Saída",width:120,render:a=>e.jsx("span",{children:O(a.saida)}),sortValue:a=>a.saida},{key:"compliance",label:"Compliance",width:180,render:a=>e.jsx(Z,{c:{cte:a.cteStatus||"unknown",mdfe:a.mdfeStatus||"unknown",ciot:a.ciotStatus||"unknown",pef:a.pefStatus||"unknown"}})},{key:"valor",label:"Valor",width:100,align:"right",render:a=>e.jsx("span",{className:"font-mono",children:a.valor.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}),sortValue:a=>a.valor}];return g.useEffect(()=>{const a=m.get("dispatch");if(!a||t)return;const o=j.find(x=>x.id===a);o&&f(o)},[j,m]),e.jsxs(e.Fragment,{children:[l&&e.jsx("div",{className:"mb-3",children:e.jsx(z,{error:l,onRetry:n,inline:!0})}),e.jsx("div",{className:"flex justify-end mb-2",children:e.jsx(Ie,{})}),e.jsx(de,{rows:B,rowKey:a=>a.id,columns:W,loading:u,filterChips:[{key:"todas",label:"Todas",active:d==="todas",onClick:()=>c("todas")},{key:"hoje",label:"Hoje",active:d==="hoje",onClick:()=>c("hoje")},{key:"em_rota",label:"Em rota",active:d==="em_rota",onClick:()=>c("em_rota")},{key:"sem_motorista",label:"Sem motorista",active:d==="sem_motorista",onClick:()=>c("sem_motorista")}
1,{key:"doc_pendente",label:"Doc pendente",active:d==="doc_pendente",onClick:()=>c("doc_pendente")},{key:"urgencia",label:"Por urgência",active:d==="urgencia",onClick:()=>c("urgencia")}],bulkActions:[{key:"cte",label:"Emitir CT-e",icon:e.jsx(be,{className:"w-3.5 h-3.5"}),run:async a=>{a.length>1&&h({kind:"info",title:`Abrindo a primeira de ${a.length} — o CT-e é emitido uma viagem por vez.`}),y(`/documentos?tab=emitir&emitCte=${a[0].id}`)}},{key:"msg",label:"Mandar WhatsApp",icon:e.jsx(ye,{className:"w-3.5 h-3.5"}),run:a=>_(a)},{key:"cancel",label:"Cancelar",icon:e.jsx(je,{className:"w-3.5 h-3.5"}),variant:"destructive",run:a=>p({rows:a})}],swipeRight:{label:"Concluir",color:"#10B981",run:a=>L(a)},swipeLeft:{label:"Cancelar",color:"#EF4444",run:a=>p({rows:[a]})},onRowOpen:a=>f(a),onCreate:s,createLabel:"Nova viagem",emptyTitle:"Sem viagens aqui.",emptyBody:"Ajuste os filtros ou crie a primeira viagem.",adaCard:B.length>0&&j.filter(a=>a.motorista==="—").length>=3?e.jsx(ke,{variant:"warn",title:`${j.filter(a=>a.motorista==="—").length} viagens sem motorista designado.`,body:"Quer que eu sugira motoristas disponíveis baseado em proximidade e histórico?",actions:[{label:"Sim, sugerir",onClick:()=>{const a=j.filter(o=>o.motorista==="—");ne(`Tenho ${a.length} viagens sem motorista designado: ${a.slice(0,8).map(o=>`${o.numero} (${o.cliente}, saída ${O(o.saida)||"a definir"})`).join("; ")}. Sugira motoristas disponíveis para cada uma, considerando proximidade, jornada e histórico.`)},variant:"primary"},{label:"Ver lista",onClick:()=>c("sem_motorista"),variant:"ghost"}]}):void 0}),e.jsx(ce,{open:!!A,onClose:()=>L(null),title:A?`Concluir a viagem ${A.numero}?`:"",description:"Marca a chegada no destino. O POD e o encerramento do MDF-e seguem pelo fluxo normal.",confirmLabel:"Concluir",onConfirm:()=>A?G(A):void 0}),e.jsx(Re,{open:!!N,titulo:N?N.rows.length===1?`Cancelar a viagem ${N.rows[0].numero}?`:`Cancelar ${N.rows.length} viagens?`:"",ocupado:I,onClose:()=>p(null),onConfirm:a=>N?U(N.rows,a):void 0}),e.jsx(ue,{open:!!t,onClose:()=>f(null),title:t?`${t.numero} — ${t.cliente}`:"",subtitle:t&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:((M=te[t.status])==null?void 0:M.label)||t.status}),e.jsx(Z,{c:{cte:t.cteStatus||"unknown",mdfe:t.mdfeStatus||"unknown",ciot:t.ciotStatus||"unknown",pef:t.pefStatus||"unknown"}})]}),tabs:[{key:"resumo",label:"Resumo",content:t&&e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(w,{label:"Cliente",value:t.cliente}),e.jsx(w,{label:"Motorista",value:t.aguardandoAceite?"Aguardando aceite do condutor do MDF-e":t.motorista}),e.jsx(w,{label:"Veículo",value:t.veiculo}),e.jsx(w,{label:"Saída",value:O(t.saida)||"—"}),e.jsx(w,{label:"Valor",value:t.valor.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}),t.chaveMdfe&&e.jsx(w,{label:"MDF-e",value:`…${t.chaveMdfe.slice(-10)}`}),e.jsx(Oe,{row:t})]})},...t!=null&&t.chaveMdfe?[{key:"defesa",label:"Defesa",content:e.jsx(_e,{chave:t.chaveMdfe})}]:[],{key:"semaforo",label:"Semáforo",badge:t!=null&&t.gateLiberacao?"⚠":t!=null&&t.gateApproved?"✓":void 0,content:t&&e.jsx(Be,{dispatchId:t.id,driverId:t.driverId,vehiclePlaca:t.vehiclePlate,chaveMdfe:t.chaveMdfe,gateApproved:t.gateApproved,gateLiberacao:t.gateLiberacao,onMudou:()=>n()})},{key:"timeline",label:"Timeline",content:t&&e.jsx(Te,{dispatchId:t.id})},{key:"documentos",label:"Documentos",content:t&&e.jsx(Pe,{row:t,onEmitir:()=>y(`/documentos?tab=emitir&emitCte=${t.id}`)})},{key:"atividade",label:"Atividade",content:t&&e.jsx(we,{objectType:"viagem",objectId:t.id})},{key:"pod",label:"POD",content:t&&e.jsx(Ae,{dispatchId:t.id})},{key:"financeiro",label:"Financeiro",content:t&&e.jsx(qe,{row:t})},{key:"comentarios",label:"Comentários",content:t&&e.jsx(Ce,{objectType:"viagem",objectId:t.id})}],size:"lg"})]})}function Te({dispatchId:s}){const{data:r,loading:u}=$(()=>b.dispatchMacros(s),[s]),l=(r==null?void 0:r.items)||[];return u?e.jsx("div",{className:"text-sm py-6 text-center",style:{color:"var(--page-text-muted)"},children:"Carregando…"}):l.length?e.jsx("div",{className:"space-y-2",children:l.map(n=>e.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full mt-2 shrink-0",style:{background:n.emergencia?"#EF4444":"#3B82F6"}}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{style:{color:"var(--page-text)"},children:n.label||n.macro}),e.jsxs("span",{className:"ml-2 text-xs",style:{color:"var(--page-text-muted)"}
1,children:[n.occurredAt?new Date(n.occurredAt).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"",n.driverName?` · ${n.driverName}`:""]})]})]},n.id))}):e.jsx("div",{className:"text-sm py-8 text-center",style:{color:"var(--page-text-muted)"},children:"Nenhuma macro nesta viagem ainda. Elas aparecem aqui na hora em que o motorista toca — refeição, abastecimento, chegada, pernoite."})}function Oe({row:s}){const{toast:r}=q(),{data:u}=$(()=>b.rotogramas({limit:50}),[]),[l,n]=g.useState(!1),[m,d]=g.useState(s.rotogramaId||""),c=u||[],t=async f=>{n(!0);try{await b.updateDispatch(s.id,{rotogramaId:f||null}),d(f),r({kind:"success",title:f?"Rotograma anexado à viagem":"Rotograma removido"})}catch(y){r({kind:"error",title:(y==null?void 0:y.message)||"Não foi possível anexar"})}finally{n(!1)}};return e.jsxs("div",{className:"flex justify-between items-center gap-2",children:[e.jsx("span",{style:{color:"var(--page-text-muted)"},children:"Rotograma"}),e.jsxs("select",{value:m,disabled:l,onChange:f=>t(f.target.value),className:"text-sm rounded-lg px-2 py-1 border max-w-[220px]",style:{background:"var(--surface-primary)",borderColor:"var(--border-primary)",color:"var(--page-text)"},children:[e.jsx("option",{value:"",children:"— nenhum —"}),c.map(f=>e.jsx("option",{value:f.id,children:f.name||f.titulo||f.id.slice(0,8)},f.id))]})]})}function w({label:s,value:r}){return e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{style:{color:"var(--page-text-muted)"},children:s}),e.jsx("span",{style:{color:"var(--page-text)"},children:r})]})}function Re({open:s,titulo:r,ocupado:u,onClose:l,onConfirm:n}){const[m,d]=g.useState("");if(g.useEffect(()=>{s&&d("")},[s]),g.useEffect(()=>{if(!s)return;const t=f=>{f.key==="Escape"&&l()};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[s,l]),!s)return null;const c=m.trim().length>=10;return e.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center p-4",style:{background:"rgba(0,0,0,0.5)"},onClick:l,children:e.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"motivo-titulo",className:"w-full max-w-md rounded-xl p-5 shadow-xl",style:{background:"var(--surface-primary)",border:"1px solid var(--border-subtle)"},onClick:t=>t.stopPropagation(),children:[e.jsx("h2",{id:"motivo-titulo",className:"text-base font-bold mb-1",style:{color:"var(--page-text)"},children:r}),e.jsx("p",{className:"text-sm mb-3",style:{color:"var(--page-text-secondary)"},children:"Informe o motivo. Ele vai para a trilha de auditoria e para o motorista."}),e.jsx("textarea",{value:m,onChange:t=>d(t.target.value),rows:3,autoFocus:!0,placeholder:"Ex.: cliente adiou a coleta para a próxima semana",className:"w-full rounded-lg px-3 py-2 text-sm",style:{background:"var(--surface-secondary)",color:"var(--page-text)",border:"1px solid var(--border-subtle)"}}),e.jsx("div",{className:"flex items-center justify-between mt-1 mb-4 text-xs",style:{color:"var(--page-text-muted)"},children:e.jsx("span",{children:c?"Pronto.":`Mínimo de 10 caracteres (${m.trim().length}/10)`})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{onClick:l,className:"px-3 py-2 rounded-lg text-sm hover-surface",style:{color:"var(--page-text-secondary)"},children:"Voltar"}),e.jsx("button",{onClick:()=>c&&n(m.trim()),disabled:!c||u,className:"px-3 py-2 rounded-lg text-sm font-semibold text-white disabled:opacity-50",style:{background:"#EF4444"},children:u?"Cancelando…":"Cancelar viagem"})]})]})})}function Pe({row:s,onEmitir:r}){const{data:u,loading:l,error:n,refetch:m}=$(()=>b.fiscalDocuments(void 0,void 0,200),[s.id]),d=g.useMemo(()=>((u==null?void 0:u.documents)||(Array.isArray(u)?u:[])).filter(f=>f.dispatchId===s.id),[u,s.id]);if(l)return e.jsx("div",{className:"text-sm py-6 text-center",style:{color:"var(--page-text-muted)"},children:"Carregando documentos…"});if(n)return e.jsx(z,{error:n,onRetry:m,inline:!0});const c=t=>({cte:"CT-e",mdfe:"MDF-e",nfe:"NF-e",nfse:"NFS-e"})[t]||(t==null?void 0:t.toUpperCase());return e.jsxs("div",{className:"space-y-3 text-sm",children:[d.length===0?e.jsx("div",{className:"py-4 text-center",style:{color:"var(--page-text-muted)"},children:"Nenhum documento fiscal emitido para esta viagem."}):e.jsx("ul",{className:"space-y-2",children:d.map(t=>e.jsxs("li",{className:"flex items-center justify-between rounded-lg px-3 py-2",style:{background:"var(--surface-secondary)"},children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium",style:{color:"var(--page-text)"},children:[c(t.tipo)," ",t.numero?`nº ${t.numero}`:""]}),e.jsx("div",{className:"font-mono text-xs",style:{color:"var(--page-text-muted)"},children:t.chave?`…${String(t.chave).slice(-12)}`:"—"})]}),e.jsx("span",{className:"text-xs font-semibold px-2 py-0.5 rounded",style:{background:t.status==="autorizado"?"#10B98122":"#F59E0B22",color:t.status==="autorizado"?"#10B981":"#B45309"},children:t.status||"—"})]},t.id))}),s.cteStatus!=="ok"&&e.jsx("button",{onClick:r,className:"w-full py-2 rounded-lg text-sm font-semibold text-white",style:{background:"var(--accent-brand)"},children:"Emitir CT-e desta viagem"})]})}function qe({row:s}){const{data:r,loading:u,error:l,refetch:n}=$(()=>b.tmsAcertos(),[s.id]),m=g.useMemo(()=>(Array.isArray(r)?r:(r==null?void 0:r.items)||[]).filter(t=>t.dispatchId===s.id),[r,s.id]),d=c=>
1(Number(c)||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"});return u?e.jsx("div",{className:"text-sm py-6 text-center",style:{color:"var(--page-text-muted)"},children:"Carregando…"}):l?e.jsx(z,{error:l,onRetry:n,inline:!0}):e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(w,{label:"Frete contratado",value:d(s.valor)}),m.length===0?e.jsx("div",{className:"py-3 text-center",style:{color:"var(--page-text-muted)"},children:"Sem acerto de frete gerado para esta viagem."}):m.map(c=>e.jsxs("div",{className:"rounded-lg px-3 py-2 space-y-1",style:{background:"var(--surface-secondary)"},children:[e.jsx(w,{label:"Acerto",value:c.status||"—"}),e.jsx(w,{label:"Adiantamento",value:d(c.adiantamento)}),e.jsx(w,{label:"Descontos",value:d((c.valorFrete||0)-(c.saldoPagar||0)-(c.adiantamento||0))}),e.jsx(w,{label:"Saldo ao motorista",value:d(c.saldoPagar)})]},c.id))]})}function O(s){if(!s)return"";try{return new Date(s).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}catch{return s}}export{sa as ViagensList};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.