PageSourceSearch

https://maestro.pontua.com.br/assets/RenegociacoesPage-CaKXcgyE.js

js pontua.com.br collected 2026-10-01 14:16:29 UTC 54,000 bytes, 1 lines download raw bytes

1import{r as i,j as e,e as Yt}from"./vendor-react-DIA7vK4g.js";import{b7 as H,b6 as jt,b8 as ze,ch as k,ba as _,bm as j,bi as Zt,es as $t,aJ as ea,bL as vt,bM as bt,bN as Nt,bO as _t,bS as ta,cd as Oe,bQ as Mt,s as mt,b2 as aa,bF as sa,bX as Rt,eI as na,eJ as Be,dY as oa,at as ia,aE as ra,bz as K,bA as ut,bB as xt,bC as pt,bD as ht,bE as U,eF as la,a1 as At,u as ca,v as da,T as ft,aa as Bt,H as ma,bq as ua,br as xa,bs as pa,bt as ha,bu as fa,bP as f,bv as ga,bw as ja,bx as va,eG as ba,eH as Na,dZ as _a,by as lt,aY as ya,O as ct,d as wa,e as Ca}from"./index-DtUVjOr4.js";import{F as Sa}from"./FinanceiroLayout-BFNsfPwP.js";import{h as ka,N as Fa,o as Da}from"./NegotiationBadge-D0zZHWh_.js";import{R as dt,a as Y}from"./radio-group-CV0oqF9i.js";import{P as Pa}from"./PageHeader-DbudfU8v.js";import{e as gt}from"./edge-function-error-Bg1_3hCh.js";import{B as qt}from"./StatusBadge-37q_xsvK.js";import{C as Aa}from"./CopyButton-v1MLcxYL.js";import{T as qa,a as Ta,b as Tt,c as Et}from"./tabs-Btg5k50n.js";import{d as zt,a as Ea,f as It}from"./billing-formatters-uNs-HNzw.js";import{N as Ia}from"./NegotiationAuthorCell-CEcocjEs.js";import{a as $a}from"./negotiation-interest-DkJbZlet.js";import{E as Ma}from"./eye-DZWf3ZF4.js";import"./vendor-docs-BA9xu9ak.js";import"./vendor-utils-DWHjTIse.js";import"./vendor-supabase-_bOAMmkC.js";import"./useSandboxConfig-H_pzAYpM.js";import"./GlobalSearch-CILhhYPj.js";import"./command-8X5Fvwln.js";import"./repeat-sulmqLMn.js";import"./corner-down-left-BYgMx1Bm.js";import"./clock-x8uDBefL.js";import"./AssignmentDialogs-9SSh1vBf.js";import"./scroll-area-DFJSP9HM.js";import"./useAssignments-D_S3BN6V.js";import"./archive-q1simTCW.js";const Ce=500,Ra="RENEGOCIACAO DE TITULOS";function we(s){return String(s??"").replace(/[\u0000-\u001F\u007F]+/g," ").replace(/\s{2,}/g," ").trim().slice(0,Ce)}function Ba(s){const c=we(s.custom);if(c)return c;const d=(s.invoiceNumbers??[]).map(l=>String(l??"").trim()).filter(Boolean);let x=Ra;if(s.negotiationNumber&&(x+=` ${String(s.negotiationNumber).trim()}`),d.length===0)return we(x);const b=[];for(const l of d){const N=[...b,l],T=d.length-N.length;if(`${x} - ref. ${N.join(", ")}${T>0?` e mais ${T} fatura${T>1?"s":""}`:""}`.length>Ce)break;b.push(l)}if(b.length===0)return we(`${x} - ref. ${d.length} faturas`);const v=d.length-b.length;return we(`${x} - ref. ${b.join(", ")}${v>0?` e mais ${v} fatura${v>1?"s":""}`:""}`)}const za=15;function Oa(){return H({queryKey:["billing-neg-config"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s}=await _.from("billing_settings").select("value").eq("key","negotiation_config").maybeSingle(),c=(s==null?void 0:s.value)||{};return{max_discount_percent:c.max_discount_percent??20,max_installments:c.max_installments??10,min_installment_amount:c.min_installment_amount??50,discount_approval_threshold_percent:c.discount_approval_threshold_percent??za,interest_free_installments:c.interest_free_installments??6,monthly_interest_percent:c.monthly_interest_percent??1.99}}})}const Ot="*, customers(company_name), requester:profiles!negotiation_approval_requests_requested_by_fkey(full_name, email, avatar_url)";function Va(s){return H({queryKey:["negotiation-approvals",s],queryFn:async()=>{let c=_.from("negotiation_approval_requests").select(Ot).order("created_at",{ascending:!1}).limit(200);c=s==="pendente"?c.eq("status","pendente"):c.neq("status","pendente");const{data:d,error:x}=await c;if(x)throw x;return d??[]}})}function La(s,c){return H({queryKey:["negotiation-approval-usable",s],enabled:!!s,queryFn:async()=>{const{data:d,error:x}=await _.from("negotiation_approval_requests").select(Ot).eq("customer_id",s).eq("status","aprovada").is("consumed_at",null).order("created_at",{ascending:!1});if(x)throw x;return d??[]},select:d=>d.filter(x=>Number(x.discount_percent??0)+.001>=c)})}function Ka(){const s=jt();return ze({mutationFn:async c=>{var v;const{data:d}=await _.auth.getUser(),x=(v=d.user)==null?void 0:v.id;if(!x)throw new Error("Sessão expirada. Faça login novamente.");const{error:b}=await _.from("negotiation_approval_requests").insert({...c,requested_by:x});if(b)throw b},onSuccess:()=>{k({title:"Autorização solicitada",description:"O gestor de cobrança foi acionado para análise."}),s.invalidateQueries({queryKey:["negotiation-approvals"]}
1),s.invalidateQueries({queryKey:["negotiation-approval-usable"]})},onError:c=>k({title:"Erro ao solicitar autorização",description:c.message,variant:"destructive"})})}function Ja(){const s=jt();return ze({mutationFn:async c=>{var b;const{data:d}=await _.auth.getUser(),{error:x}=await _.from("negotiation_approval_requests").update({status:c.decision,approved_by:((b=d.user)==null?void 0:b.id)??null,decided_at:new Date().toISOString(),motivo_decisao:c.motivo||null}).eq("id",c.id).eq("status","pendente");if(x)throw x},onSuccess:(c,d)=>{k({title:d.decision==="aprovada"?"Desconto autorizado":"Solicitação recusada"}),s.invalidateQueries({queryKey:["negotiation-approvals"]}),s.invalidateQueries({queryKey:["negotiation-approval-usable"]})},onError:c=>k({title:"Erro ao decidir",description:c.message,variant:"destructive"})})}const Qa={pendente:"Pendente",aprovada:"Aprovada",recusada:"Recusada",cancelada:"Cancelada"};function Ua({status:s}){const c=s==="aprovada"?"default":s==="recusada"?"destructive":"secondary";return e.jsx(sa,{variant:c,children:Qa[s]||s})}function Ha({req:s,canDecide:c,onDecide:d}){var b,v,l,N;const x=Number(s.discount_percent??0);return e.jsxs("div",{className:"rounded-2xl border bg-card p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:zt((b=s.customers)==null?void 0:b.company_name)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[((v=s.invoice_ids)==null?void 0:v.length)||0," fatura(s) · solicitado por"," ",((l=s.requester)==null?void 0:l.full_name)||((N=s.requester)==null?void 0:N.email)||"—"," · ",Ea(s.created_at)]})]}),e.jsx(Ua,{status:s.status})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Valor original"}),e.jsx("p",{className:"font-mono tabular-nums",children:It(Number(s.original_total))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Desconto pedido"}),e.jsxs("p",{className:"font-mono tabular-nums text-amber-600 dark:text-amber-400",children:[x.toFixed(2),"% (",It(Number(s.discount_amount)),")"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teto sem autorização"}),e.jsxs("p",{className:"font-mono tabular-nums",children:[Number(s.threshold_percent).toFixed(2),"%"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Parcelamento"}),e.jsxs("p",{className:"font-mono tabular-nums",children:[s.installments,"x"]})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"text-foreground font-medium",children:"Justificativa: "}),s.justificativa]}),s.status!=="pendente"&&s.motivo_decisao&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Motivo da decisão: ",s.motivo_decisao]}),s.status==="pendente"&&c&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(j,{size:"sm",onClick:()=>d(s,"aprovada"),children:[e.jsx(mt,{className:"h-4 w-4 mr-1"})," Aprovar"]}),e.jsxs(j,{size:"sm",variant:"destructive",onClick:()=>d(s,"recusada"),children:[e.jsx(aa,{className:"h-4 w-4 mr-1"})," Recusar"]})]})]})}function Xa({canDecide:s}){const[c,d]=i.useState("pendente"),{data:x,isLoading:b}=Va(c),v=Ja(),[l,N]=i.useState(null),[T,E]=i.useState("");return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex gap-2",children:["pendente","decididas"].map(u=>e.jsx(j,{size:"sm",variant:c===u?"default":"outline",onClick:()=>d(u),children:u==="pendente"?"Pendentes":"Decididas"},u))}),b?e.jsx("div",{className:"space-y-3",children:[0,1].map(u=>e.jsx(Zt,{className:"h-32 w-full rounded-2xl"},u))}):(x||[]).length===0?e.jsx("div",{className:"rounded-2xl border bg-card",children:e.jsx($t,{icon:ea,title:"Nenhuma solicitação",description:c==="pendente"?"Não há descontos aguardando autorização.":"Nenhuma decisão registrada ainda."})}):e.jsx("div",{className:"space-y-3",children:(x||[]).map(u=>e.jsx(Ha,{req:u,canDecide:s,onDecide:(X,G)=>{N({req:X,decision:G}),E("")}},u.id))}),e.jsx(vt,{open:!!l,onOpenChange:u=>!u&&N(null),children:e.jsxs(bt,{className:"max-w-md",children:[e.jsxs(Nt,{children:[e.jsx(_t,{children:(l==null?void 0:l.decision)==="aprovada"?"Aprovar desconto":"Recusar solicitação"}),e.jsx(ta,{children:(l==null?void 0:l.decision)==="aprovada"?"O desconto aprovado poderá ser aplicado uma única vez na renegociação deste cliente.":"A analista precisará ajustar o desconto para dentro do teto."})]}),e.jsx(Oe,{placeholder:"Motivo da decisão (opcional)",value:T,onChange:u=>E(u.target.value)}),e.jsxs(Mt,{children:[e.jsx(j,{variant:"outline",onClick:()=>N(null),children:"Cancelar"}),e.jsx(j,{variant:(l==null?void 0:l.decision)==="recusada"?"destructive":"default",disabled:v.isPending,onClick:()=>l&&v.mutate({id:l.req.id,decision:l.decision,motivo:T},{onSuccess:()=>N(null)}),children:"Confirmar"})]})]})})]})}const ye=25,Ga=[],g=s=>new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format(s),Se=s=>s?new Date(s).toLocaleDateString("pt-BR"):"—";function Ss(){var fe;const s=jt(),{hasPermission:c}=Rt(),d=c("financeiro.renegociacoes.create"),x=c("financeiro.cobranca.manage"),b=d||x,[v,l]=i.useState(0),[N,T]=i.useState(""),[E,u]=i.useState("all"),[X,G]=i.useState(!1),[I,A]=i.useState(null),[R,ke]=Yt(),Z=R.get("customer_id"),F=i.useMemo(()=>(R.get("invoice_ids")||"").split(",").map(a=>
1a.trim()).filter(Boolean),[R]),[xe,ee]=i.useState(!1);i.useEffect(()=>{Z&&(d?G(!0):(ee(!0),k({title:"Sem permissão para criar renegociações",description:"Solicite o acesso ao administrador para criar renegociações.",variant:"destructive"})))},[Z,d]);const ie=()=>{if(G(!1),Z||R.get("invoice_ids")){const a=new URLSearchParams(R);a.delete("customer_id"),a.delete("invoice_ids"),ke(a,{replace:!0})}s.invalidateQueries({queryKey:["billing-negotiations"]})},[P,te]=i.useState(null),[re,pe]=i.useState(""),[le,Ve]=i.useState([]),[Fe,Le]=i.useState([]),{data:J,isLoading:De}=H({queryKey:["billing-negotiations",v,N,E],queryFn:async()=>{let a=_.from("negotiations").select("*, customers!negotiations_customer_id_fkey!inner(company_name), negotiation_items(count), author:profiles!negotiations_created_by_fkey(full_name, email, avatar_url)",{count:"exact"}).eq("is_sandbox",!1).order("created_at",{ascending:!1});N&&(a=a.or(`negotiation_number.ilike.%${N}%,customers.company_name.ilike.%${N}%`)),E!=="all"&&(a=a.eq("status",E));const n=v*ye;a=a.range(n,n+ye-1);const{data:h,error:p,count:de}=await a;if(p)throw p;return{negotiations:h||[],total:de||0}}}),M=(J==null?void 0:J.negotiations)??Ga,ce=(J==null?void 0:J.total)||0,he=Math.ceil(ce/ye),Ke=v*ye+1,ae=Math.min((v+1)*ye,ce),{data:B}=H({queryKey:["billing-negotiation-detail",I],queryFn:async()=>{const[a,n]=await Promise.all([_.from("negotiations").select("*, customers!negotiations_customer_id_fkey(company_name, document, email)").eq("id",I).single(),_.from("negotiation_items").select("*, invoices(invoice_number, due_date, total_amount, status)").eq("negotiation_id",I)]);if(a.error)throw a.error;return{negotiation:a.data,items:n.data||[]}},enabled:!!I}),z=ze({mutationFn:async a=>{const{data:n,error:h}=await _.functions.invoke("create-negotiation-boleto",{body:{negotiation_id:a.id,due_date:a.due_date||new Date(Date.now()+2592e5).toISOString().slice(0,10)}});if(h)throw new Error(await gt(h));if(n!=null&&n.error)throw new Error(String(n.error));return n},onSuccess:()=>{k({title:"Boleto gerado",description:"O link de pagamento foi atualizado."}),s.invalidateQueries({queryKey:["billing-negotiations"]}),I&&s.invalidateQueries({queryKey:["billing-negotiation-detail",I]})},onError:a=>k({title:"Erro ao gerar boleto",description:a.message,variant:"destructive"})}),se=ze({mutationFn:async a=>{const{data:n,error:h}=await _.functions.invoke("cancel-negotiation",{body:{negotiation_id:a,reason:re.trim()||null}});if(h)throw new Error(await gt(h));if(n!=null&&n.error)throw new Error(String(n.error));return n},onSuccess:a=>{s.invalidateQueries({queryKey:["billing-negotiations"]}),s.invalidateQueries({queryKey:["negotiation-invoices"]}),I&&s.invalidateQueries({queryKey:["billing-negotiation-detail",I]}),te(null),pe("");const n=[a!=null&&a.invoice_canceled?"fatura cancelada":null,a!=null&&a.boleto_queued?"boleto em cancelamento na Omie":null,a!=null&&a.reopened_invoices?`${a.reopened_invoices} fatura(s) reabertas`:null].filter(Boolean);k({title:"Renegociação cancelada",description:n.length?n.join(" · "):void 0})},onError:a=>k({title:"Erro",description:a.message,variant:"destructive"})}),q=na(),Pe=i.useMemo(()=>M.some(a=>Number(a.discount_amount||0)>0),[M]),ne=i.useMemo(()=>[q.accessor("negotiation_number",{header:"Nº",cell:a=>e.jsx("span",{className:"font-mono text-sm tabular-nums",children:a.getValue()}),meta:{filterType:"text"}}),q.accessor("company_name",{header:"Empresa",cell:a=>e.jsx("span",{className:"font-medium block truncate max-w-[240px]",children:a.getValue()}),meta:{filterType:"text"}}),q.accessor("invoice_count",{header:"Faturas agrupadas",cell:a=>e.jsx("span",{className:"inline-flex items-center justify-center min-w-[2rem] rounded-full bg-muted px-2 py-0.5 text-xs font-medium tabular-nums",children:a.getValue()}),meta:{filterType:"number",headerClassName:"text-center",cellClassName:"text-center"},filterFn:Be}),q.accessor("original_total",{header:"Valor original",cell:a=>{const n=a.row.original,h=Number(n.discount_amount||0)>0;return e.jsx("span",{className:`font-mono tabular-nums text-sm ${h?"line-through text-muted-foreground":"text-foreground"}`,children:g(a.getValue())})},meta:{filterType:"number",headerClassName:"text-right",cellClassName:"text-right"},filterFn:Be}),...Pe?[q.display({id:"discount",header:"Desconto",meta:{headerClassName:"text-center",cellClassName:"text-center"},cell:a=>{const n=a.row.original;if(!Number(n.discount_amount||0))return e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"});const h=n.discount_percent?`${Number(n.discount_percent).toFixed(2)}%`:g(Number(n.discount_amount));return e.jsx("span",{className:"text-sm font-medium text-emerald-600 dark:text-emerald-400",children:h})},enableSorting:!1})]:[],q.accessor("final_total",{header:"Valor final",cell:a=>e.jsx("span",{className:"font-mono tabular-nums text-sm font-bold text-foreground",children:g(a.getValue())}),meta:{filterType:"number",headerClassName:"text-right",cellClassName:"text-right"},filterFn:Be}),q.display({id:"parcelas",header:"Parcelamento",cell:a=>{const n=a.row.original;return e.jsx("span",{className:"text-sm font-mono tabular-nums",children:n.installments&&n.installment_amount?`${n.installments}x ${g(n.installment_amount)}`:"—"})}}),q.accessor("due_date",{header:"Próximo vencimento",cell:a=>e.jsx("span",{className:"text-sm tabular-nums",children:Se(a.getValue())}),meta:{headerClassName:"whitespace-nowrap"}}),q.display({id:"autor",header:"Autor",cell:a=>e.jsx(Ia,{origem:a.row.original.origem,author:a.row.original.author}),enableSorting:!1}),q.accessor("status",{header:"Status",cell:a=>e.jsx(qt,{status:a.getValue()||"pending"}),meta:{filterType:"enum",enumOptions:[{value:"pending",label:"Pendente"},{value:"active",label:"Ativa"},{value:"paid",label:"Paga"},{value:"defaulted",label:"Inadimplida"},{value:"canceled",label:"Cancelada"}]},filterFn:Be}),q.display({id:"actions",header:"Ação",meta:{headerClassName:"w-[40px]"},cell:a=>e.jsx(j,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:n=>{n.stopPropagation(),A(a.row.original.id)},children:e.jsx(Ma,{className:"h-4 w-4"})}),enableSorting:!1})],[Pe]),Je=i.useMemo(()=>M.filter(a=>{var h;const n=a.negotiation_items;return(((h=n==null?void 0:n[0])==null?void 0:h.count)??0)>0}).map(a=>{var p;const n=a.customers,h=a.negotiation_items;return{id:a.id,negotiation_number:a.negotiation_number,company_name:zt(n==null?void 0:n.company_name),invoice_count:((p=h==null?void 0:h[0])==null?void 0:p.count)??0,due_date:a.due_date??null,origem:a.origem??null,author:a.author??null,original_total:a.original_total,discount_percent:a.discount_percent,discount_amount:a.discount_amount,final_total:a.final_total,installments:a.installments,installment_amount:a.installment_amount,status:a.status}}),[M]),Ae=oa({data:Je,columns:ne,state:{sorting:le,columnFilters:Fe},onSortingChange:Ve,onColumnFiltersChange:Le,getCoreRowModel:_a(),getSortedRowModel:Na(),getFilteredRowModel:ba()});return e.jsxs(Sa,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(Pa,{title:"Renegociações",count:ce,countLabel:"renegociações",actions:d?e.jsxs(j,{onClick:()=>G(!0),children:[e.jsx(ia,{className:"h-4 w-4 mr-2"})," Nova Renegociação"]}):void 0}),xe&&!d&&e.jsx("div",{className:"rounded-2xl border border-destructive/30 bg-destructive/10 p-4 text-sm text-destructive",children:"Você não tem permissão para criar renegociações. Solicite o acesso ao administrador."}),e.jsxs(qa,{defaultValue:"lista",className:"space-y-4",children:[e.jsxs(Ta,{children:[e.jsx(Tt,{value:"lista",children:"Renegociações"}),e.jsx(Tt,{value:"autorizacoes",children:"Autorizações de desconto"})]}),e.jsxs(Et,{value:"lista",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-sm",children:[e.jsx(ra,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(K,{placeholder:"Buscar por nº ou empresa...",className:"pl-9",value:N,onChange:a=>{T(a.target.value),l(0)}})]}),e.jsxs(ut,{value:E,onValueChange:a=>{u(a),l(0)},children:[e.jsx(xt,{className:"w-[150px]",children:e.jsx(pt,{placeholder:"Status"})}),e.jsxs(ht,{children:[e.jsx(U,{value:"all",children:"Todas"}),e.jsx(U,{value:"pending",children:"Pendente"}),e.jsx(U,{value:"active",children:"Ativa"}),e.jsx(U,{value:"paid",children:"Paga"}),e.jsx(U,{value:"defaulted",children:"Inadimplida"}),e.jsx(U,{value:"canceled",children:"Cancelada"})]})]})]}),e.jsx("div",{className:"rounded-2xl border bg-card overflow-x-auto",children:e.jsx(la,{table:Ae,columns:ne.length,isLoading:De,emptyState:e.jsx($t,{icon:At,title:"Nenhuma renegociação encontrada",description:"Crie uma nova renegociação para começar"}),onRowClick:a=>A(a.id)})}),he>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Mostrando ",Ke,"–",ae," de ",ce," renegociações"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(j,{variant:"outline",size:"sm",disabled:v===0,onClick:()=>l(a=>a-1),children:e.jsx(ca,{className:"h-4 w-4"})}),e.jsx(j,{variant:"outline",size:"sm",disabled:v>=he-1,onClick:()=>l(a=>a+1),children:e.jsx(da,{className:"h-4 w-4"})})]})]})]}),e.jsx(Et,{value:"autorizacoes",children:e.jsx(Xa,{canDecide:x})})]})]}),e.jsx(vt,{open:!!I,onOpenChange:a=>!a&&A(null),children:e.jsxs(bt,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(Nt,{children:e.jsxs(_t,{className:"flex items-center gap-2",children:[e.jsx(At,{className:"h-5 w-5"}),"Renegociação ",(fe=B==null?void 0:B.negotiation)==null?void 0:fe.negotiation_number]})}),(B==null?void 0:B.negotiation)&&(()=>{const a=B.negotiation,n=a.customers;return e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Empresa:"})," ",n==null?void 0:n.company_name]}),(n==null?void 0:n.document)&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Documento:"})," ",n.document]}),(n==null?void 0:n.email)&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Email:"})," ",n.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Status:"})," ",e.jsx(qt,{status:a.status||"pending"})]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Criada em:"}
1)," ",Se(a.created_at)]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Valores"}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Original:"})," ",e.jsx("span",{className:"font-mono tabular-nums line-through text-muted-foreground",children:g(a.original_total)})]}),a.discount_percent&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Desconto:"})," ",e.jsxs("span",{className:"text-emerald-600 dark:text-emerald-400 font-medium",children:[a.discount_percent,"%"]})]}),a.discount_amount&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Desconto (R$):"})," ",e.jsx("span",{className:"font-mono tabular-nums",children:g(a.discount_amount)})]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Final:"})," ",e.jsx("span",{className:"font-bold font-mono tabular-nums",children:g(a.final_total)})]}),a.installments&&a.installment_amount&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Parcelas:"})," ",e.jsxs("span",{className:"font-mono tabular-nums",children:[a.installments,"x ",g(a.installment_amount)]})]})]}),B.items.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Faturas incluídas"}),e.jsx("div",{className:"rounded-xl border divide-y",children:B.items.map(h=>{const p=h.invoices;return e.jsxs("div",{className:"flex justify-between p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-mono tabular-nums text-sm",children:(p==null?void 0:p.invoice_number)||"—"}),e.jsxs("p",{className:"text-muted-foreground text-xs",children:["Venc: ",Se((p==null?void 0:p.due_date)||null)]})]}),e.jsx("p",{className:"font-medium font-mono tabular-nums",children:g(h.original_amount)})]},h.id)})})]}),a.checkout_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Link de Pagamento"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Aa,{value:a.checkout_url,truncate:40}),e.jsx(j,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>window.open(a.checkout_url,"_blank"),children:e.jsx(ft,{className:"h-4 w-4"})})]})]}),a.gateway==="omie"&&!a.checkout_url&&a.status!=="canceled"&&a.status!=="paid"&&e.jsxs(j,{size:"sm",variant:"outline",disabled:z.isPending,onClick:()=>z.mutate({id:a.id,due_date:a.due_date}),children:[z.isPending&&e.jsx(Bt,{className:"h-4 w-4 mr-1 animate-spin"}),"Gerar boleto"]}),a.notes&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Observações"}),e.jsx("p",{className:"text-muted-foreground",children:a.notes})]}),b&&a.status!=="canceled"&&a.status!=="paid"&&e.jsxs(j,{variant:"destructive",size:"sm",onClick:()=>te(a.id),children:[e.jsx(ma,{className:"h-4 w-4 mr-2"})," Cancelar Renegociação"]})]})})()]})}),e.jsx(ua,{open:!!P,onOpenChange:a=>!a&&te(null),children:e.jsxs(xa,{children:[e.jsxs(pa,{children:[e.jsx(ha,{children:"Cancelar renegociação?"}),e.jsx(fa,{children:"Esta ação não pode ser desfeita. Ao confirmar: a fatura da renegociação é cancelada, o boleto é enviado para cancelamento na Omie e as faturas originais voltam para em aberto."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{htmlFor:"cancel-neg-reason",children:"Motivo (opcional)"}),e.jsx(Oe,{id:"cancel-neg-reason",value:re,onChange:a=>pe(a.target.value),placeholder:"Ex.: cliente desistiu da renegociação",rows:2})]}),e.jsxs(ga,{children:[e.jsx(ja,{disabled:se.isPending,children:"Voltar"}),e.jsx(va,{disabled:se.isPending,onClick:a=>{a.preventDefault(),P&&se.mutate(P)},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:se.isPending?"Cancelando...":"Confirmar Cancelamento"})]})]})}),X&&e.jsx(Wa,{open:X,onClose:ie,initialCustomerId:Z,initialInvoiceIds:F})]})}function Wa({open:s,onClose:c,initialCustomerId:d,initialInvoiceIds:x}){const{hasPermission:b}=Rt(),v=b("financeiro.renegociacoes.create"),[l,N]=i.useState(1),[T,E]=i.useState(""),[u,X]=i.useState(d??null),[G,I]=i.useState(""),[A,R]=i.useState(x??[]);i.useEffect(()=>{d&&(X(t=>(t&&t!==d&&a(),d)),_.from("customers").select("company_name").eq("id",d).maybeSingle().then(({data:t})=>{t!=null&&t.company_name&&(I(t.company_name),E(t.company_name))}))},[d]);const[ke,Z]=i.useState(""),[F,xe]=i.useState(""),[ee,ie]=i.useState(!1),[P,te]=i.useState("conjunta"),[re,pe]=i.useState(""),[le,Ve]=i.useState("percent"),[Fe,Le]=i.useState(""),[J,De]=i.useState("1"),[M,ce]=i.useState(()=>new Set(["pix","cartao"])),[he,Ke]=i.useState(""),[ae,B]=i.useState(""),[z,se]=i.useState("apos_pagamento"),[q,Pe]=i.useState(""),[ne,Je]=i.useState([]),[Ae,fe]=i.useState(!1);function a(){R([]),Z(""),xe(""),ie(!1),te("conjunta"),pe("")}function n(t,o){u!==t&&a(),X(t),I(o),E(o)}const{data:h}=H({queryKey:["billing-neg-customers",T],queryFn:async()=>{let t=_.from("customers").select("id, company_name, document").eq("status","active").eq("is_sandbox",!1).limit(20);T&&(t=t.ilike("company_name",`%${T}%`));const{data:o}=await t;return o||[]},enabled:l===1}),{data:p}=H({queryKey:["billing-neg-invoices",u],queryFn:async()=>{const{data:t}=await _.from("invoices").select("*, negotiation:negotiations!fk_invoices_negotiation(id, negotiation_number, status, final_total, due_date, checkout_url)").eq("customer_id",u).in("status",["overdue","pending","past_due"]).order("due_date",{ascending:!0});return t||[]},enabled:!!u&&l===1}),de=t=>ka(t),ge=i.useMemo(()=>(p||[]).filter(t=>!de(t)),[p]),yt=(p||[]).length-ge.length,Vt=i.useMemo(()=>{const t=new Map;for(const o of p||[]){const r=o==null?void 0:o.negotiation;if(!de(o)||!(r!=null&&r.id))continue;const m=t.get(r.id);m?m.count+=1:t.set(r.id,{number:r.negotiation_number,total:Number(r.final_total||0),dueDate:r.due_date??null,url:r.checkout_url??null,count:1})}return Array.from(t.values())},[p]);i.useEffect(()=>{if(!(p!=null&&p.length))return;const t=p.filter(r=>de(r)&&A.includes(r.id));if(!t.length)return;const o=Array.from(new Set(t.map(r=>{var m;return(m=r.negotiation)==null?void 0:m.negotiation_number}
1).filter(Boolean)));R(r=>r.filter(m=>!t.some(C=>C.id===m))),k({title:"Faturas já renegociadas foram desmarcadas",description:`${t.length} fatura(s) já estão em uma renegociação ativa${o.length?` (${o.join(", ")})`:""}.`})},[p]);const{data:je}=H({queryKey:["billing-neg-subscriptions",u],queryFn:async()=>{const{data:t}=await _.from("subscriptions").select("id, status, plan_name, mrr_amount").eq("customer_id",u).neq("status","canceled").order("created_at",{ascending:!1});return t||[]},enabled:!!u});i.useEffect(()=>{!F&&je&&je.length===1&&xe(je[0].id)},[je,F]),i.useEffect(()=>{ie(!!F)},[F]);const{data:V}=H({queryKey:["billing-neg-splits",F],queryFn:async()=>{const{data:t}=await _.from("subscription_billing_splits").select("id, amount, target_customer_id, customers:target_customer_id(company_name, document)").eq("subscription_id",F).eq("is_active",!0).order("amount",{ascending:!1});return t||[]},enabled:!!F}),qe=(V||[]).length>1;i.useEffect(()=>{!qe&&P!=="conjunta"&&te("conjunta")},[qe,P]);const{data:y}=Oa(),Qe=(y==null?void 0:y.max_discount_percent)??20,Te=(y==null?void 0:y.max_installments)??10,Ue=(y==null?void 0:y.min_installment_amount)??50,He=(y==null?void 0:y.interest_free_installments)??6,Xe=(y==null?void 0:y.monthly_interest_percent)??1.99,me=(p||[]).filter(t=>A.includes(t.id)),Lt=me.reduce((t,o)=>t+Number(o.total_amount||0),0),Ee=me.filter(t=>(t.nfse_emitted_at||t.nfe_issued_at||t.nfse_numero)&&t.nfe_status!=="canceled"),ve=Ee.length>0,Ge=Ba({invoiceNumbers:me.map(t=>t.invoice_number)}),We=we(q)||Ge;i.useEffect(()=>{ve&&z!=="nao_emitir"&&se("nao_emitir")},[ve]);const Ye=parseFloat(String(ke).replace(",","."))||0,be=Ye>0,W=be?Ye:Lt,wt=t=>t?Math.max(0,Math.floor((Date.now()-new Date(t).getTime())/864e5)):0,Kt=me.filter(t=>wt(t.due_date)>0).length,Ct=me.reduce((t,o)=>Math.max(t,wt(o.due_date)),0),Ze=parseFloat(Fe)||0,Ne=le==="percent"?W*(Ze/100):Ze,_e=Math.max(W-Ne,0),D=parseInt(J)||1,Ie=M.has("cartao"),et=M.has("boleto"),Q=$a(_e,!Ie?1:D,{interestFreeInstallments:He,monthlyInterestPercent:Xe}),St=Q.installmentAmount,tt=i.useMemo(()=>{if(P!=="individual"||!(V!=null&&V.length))return[];const t=V.reduce((r,m)=>r+Number(m.amount||0),0);if(t<=0)return[];let o=0;return V.map((r,m)=>{var S,ue;const C=m===V.length-1,w=C?Math.round((_e-o)*100)/100:Math.round(_e*(Number(r.amount||0)/t)*100)/100;return C||(o+=w),{id:r.target_customer_id,name:((S=r.customers)==null?void 0:S.company_name)||"—",document:((ue=r.customers)==null?void 0:ue.document)||"",amount:w}})},[P,V,_e]),Jt=!!u&&(A.length>0||be),$e=(y==null?void 0:y.discount_approval_threshold_percent)??15,oe=W>0?Ne/W*100:0,Me=oe>$e+.001,{data:Qt}=La(u,oe),L=Me&&(Qt||[])[0]||null,kt=Me&&!L,Re=L?Math.max(Qe,Number(L.discount_percent??0)):Qe,at=oe>Re+.001,Ft=Ka(),[st,Ut]=i.useState(""),O=!Ie,nt=!O&&St<Ue&&D>1,ot=et&&!ae,it=M.size===0,Dt=P==="eleito"&&!re,Ht=!it&&!kt&&!at&&!nt&&D>=1&&D<=Te&&!ot&&(!O||D===1)&&!Dt&&!(ee&&!F),$=[];v||$.push("Você não tem permissão para criar renegociações."),ee&&!F&&$.push("Selecione uma assinatura para usar o bloqueio de acesso (ou desmarque a opção)."),kt&&$.push(`Desconto acima do teto de ${$e}% exige autorização aprovada.`),at&&$.push(`Desconto acima do limite permitido (${Re}%).`),it&&$.push("Selecione ao menos uma forma de pagamento."),ot&&$.push("Informe a data de vencimento do boleto."),O&&D!==1&&$.push("Sem cartão liberado o pagamento é sempre à vista (1 parcela)."),!O&&(D<1||D>Te)&&$.push(`Número máximo de parcelas deve estar entre 1 e ${Te}.`),nt&&$.push(`Valor da parcela abaixo do mínimo de ${g(Ue)}.`),Dt&&$.push("Escolha o CNPJ que receberá a cobrança.");const Xt=async t=>{var Pt;let o=null,r=null,m=null,C=null;const{data:w,error:S}=await _.functions.invoke("negotiation-issue-link",{body:{negotiation_id:t.id,allowed_methods:Array.from(M),max_installments:Ie?D:1,boleto_due_date:et&&ae||null}});if(S||(w==null?void 0:w.ok)===!1){const rt=(w==null?void 0:w.error)||await gt(S)||String(S);k({title:`${t.negotiation_number}: erro ao gerar link`,description:rt,variant:"destructive"})}else o=w.url,r=w.boleto_url||null,m=w.boleto_barcode||null,C=w.pix_copy_paste||null;const ue=((Pt=tt.find(rt=>rt.id===t.target_customer_id))==null?void 0:Pt.name)??null;return{negotiation_number:t.negotiation_number,company:P==="individual"?ue:null,amount:Number(t.final_total||0),checkout_url:o,boleto_url:r,boleto_barcode:m,pix_copy_paste:C}},Gt=async()=>
1{if(!u)return;const t=Array.from(new Set(me.map(r=>r.id))),o=A.length-t.length;if(o>0&&(R(t),k({title:"Seleção ajustada",description:`${o} fatura(s) não pertencem a este cliente ou não estão em aberto e foram removidas da seleção.`}),!t.length&&!be)){k({title:"Nenhuma fatura válida",description:"Selecione as faturas em aberto do cliente ou informe um valor a negociar.",variant:"destructive"});return}fe(!0);try{const{data:r,error:m}=await _.rpc("create_negotiation_flex",{p_customer_id:u,p_invoice_ids:t.length?t:null,p_custom_total:be?Ye:null,p_discount_percent:le==="percent"?Ze:null,p_discount_amount:Ne,p_installments:O?1:D,p_interest_percent:O?0:Q.interestPercent,p_gateway:"pagarme",p_allowed_methods:Array.from(M),p_max_installments:Ie?D:1,p_notes:he||null,p_due_date:ae||null,p_origem:"analista",p_approval_request_id:(L==null?void 0:L.id)??null,p_subscription_id:F||null,p_blocks_access:ee&&!!F,p_split_mode:qe?P:"conjunta",p_target_customer_id:P==="eleito"&&re||null,p_nfse_mode:ve?"nao_emitir":z});if(m)throw m;const C=(Array.isArray(r)?r:[r]).filter(S=>S==null?void 0:S.id);if(!C.length)throw new Error("Falha ao criar renegociação");!ve&&z!=="nao_emitir"&&await _.from("negotiations").update({nfse_description:We}).in("id",C.map(S=>S.id));const w=[];for(const S of C)w.push(await Xt(S));Je(w),N(3)}catch(r){const m=String((r==null?void 0:r.message)||r),C=/row-level security|permission denied|violates row-level/i.test(m);k({title:C?"Sem permissão":"Erro ao criar renegociação",description:C?"Você não tem permissão para criar renegociações. Solicite o acesso ao administrador.":m,variant:"destructive"})}finally{fe(!1)}},Wt=t=>{const o=Math.floor((Date.now()-new Date(t).getTime())/864e5);return o>0?o:0};return e.jsx(vt,{open:s,onOpenChange:t=>!t&&c(),children:e.jsxs(bt,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Nt,{children:e.jsxs(_t,{children:[l===1&&"Selecionar Cliente e Faturas",l===2&&"Condições da Renegociação",l===3&&"Renegociação Criada"]})}),e.jsx("div",{className:"flex gap-2 mb-2",children:[1,2,3].map(t=>e.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-colors ${t<=l?"bg-primary":"bg-muted"}`},t))}),l===1&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(f,{className:"text-sm font-medium",children:"Buscar cliente"}),e.jsx(K,{placeholder:"Nome da empresa...",value:T,onChange:t=>E(t.target.value),className:"mt-1"}),h&&h.length>0&&!u&&e.jsx("div",{className:"mt-2 rounded-xl border divide-y max-h-40 overflow-y-auto",children:h.map(t=>e.jsxs("button",{className:"w-full flex justify-between items-center p-3 text-sm hover:bg-muted/50 text-left",onClick:()=>{n(t.id,t.company_name)},children:[e.jsx("span",{className:"font-medium",children:t.company_name}),e.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:t.document||""})]},t.id))}),u&&e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Selecionado:"}),e.jsx("span",{className:"text-sm font-medium",children:G}),e.jsx(j,{variant:"ghost",size:"sm",onClick:()=>{a(),X(null),I(""),E("")},children:"Trocar"})]})]}),u&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(f,{className:"text-sm font-medium",children:"Faturas em aberto"}),ge.length>0&&e.jsx(j,{variant:"ghost",size:"sm",onClick:()=>R(t=>t.length===ge.length?[]:ge.map(o=>o.id)),children:A.length===ge.length?"Limpar seleção":"Selecionar todas"})]}),yt>0&&e.jsxs("div",{className:"mt-2 rounded-xl border border-warning-line bg-warning-soft px-3 py-2 text-xs",children:[e.jsxs("p",{className:"font-semibold text-warning-deep",children:[yt," fatura(s) já estão em uma renegociação ativa e não podem ser renegociadas novamente."]}),e.jsx("ul",{className:"mt-1 space-y-1 text-ink-body",children:Vt.map(t=>e.jsxs("li",{className:"flex flex-wrap items-center gap-x-2",children:[e.jsx("span",{className:"font-medium",children:t.number}),e.jsxs("span",{children:["· ",t.count," fatura(s)"]}),e.jsxs("span",{children:["· Boleto ",g(t.total)]}),e.jsxs("span",{children:["· Vence ",Se(t.dueDate)]}),t.url&&e.jsxs("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 underline",children:["Abrir ",e.jsx(ft,{className:"h-3 w-3"})]})]},t.number))})]}),!p||p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Nenhuma fatura pendente/vencida para este cliente."}):e.jsx("div",{className:"mt-2 rounded-xl border divide-y max-h-60 overflow-y-auto",children:p.map(t=>{var C;const o=A.includes(t.id),r=Wt(t.due_date),m=de(t);return e.jsxs("label",{title:m?`Já vinculada à renegociação ${((C=t.negotiation)==null?void 0:C.negotiation_number)||""}`:void 0,className:`flex items-center gap-3 p-3 ${m?"opacity-60 cursor-not-allowed bg-muted/30":"hover:bg-muted/50 cursor-pointer"}`,children:[e.jsx(lt,{checked:o&&!m,disabled:m,onCheckedChange:w=>{m||R(S=>w?[...S,t.id]:S.filter(ue=>ue!==t.id))}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-mono text-sm tabular-nums",children:t.invoice_number}),r>0&&e.jsxs("span",{className:"text-xs text-destructive",children:[r,"d atraso"]}),m&&e.jsx(Fa,{invoice:t})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Venc: ",Se(t.due_date)]})]}),e.jsx("span",{className:"text-sm font-medium font-mono tabular-nums",children:g(t.total_amount)})]},t.id)})}),A.length>0&&e.jsxs("div",{className:"mt-3 rounded-xl border bg-muted/40 p-3 space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Faturas selecionadas"}),e.jsx("span",{className:"font-medium tabular-nums",children:A.length})]}),e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Vencidas"}),e.jsx("span",{className:"font-medium tabular-nums",children:Kt})]}),e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Maior atraso"}),e.jsx("span",{className:"font-medium tabular-nums",children:Ct>0?`${Ct} dias`:"—"})]}),e.jsxs("div",{className:"flex justify-between items-center border-t pt-2 text-sm font-bold",children:[e.jsx("span",{children:"Total selecionado"}),e.jsx("span",{className:"font-mono tabular-nums",children:g(W)})]})]}),e.jsxs("div",{className:"mt-4 rounded-xl border p-3 space-y-2",children:[e.jsx(f,{className:"text-sm font-medium",children:"Valor livre da negociação (opcional)"}),e.jsx(K,{type:"text",inputMode:"decimal",placeholder:"Ex.: 4500,00",value:ke,onChange:t=>{const o=t.target.value;(o===""||/^\d*[.,]?\d*$/.test(o))&&Z(o)}}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Informe um valor para negociar sem depender das faturas em aberto (útil quando as faturas já foram canceladas). Se preenchido, ele substitui o total selecionado."})]})]})]}),l===2&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-3 rounded-xl bg-muted/50 text-sm",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Cliente:"})," ",G]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Faturas:"})," ",A.length]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Total original:"})," ",e.jsx("span",{className:"font-bold font-mono tabular-nums",children:g(W)}),be&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:"(valor livre)"})]})]}),e.jsxs("div",{className:"rounded-xl border p-3 space-y-3",children:[e.jsx(f,{className:"text-sm font-medium",children:"Assinatura vinculada"}),e.jsxs(ut,{value:F||"none",onValueChange:t=>xe(t==="none"?"":t),children:[e.jsx(xt,{children:e.jsx(pt,{placeholder:"Selecione a assinatura"})}),e.jsxs(ht,{children:[e.jsx(U,{value:"none",children:"Sem vínculo"}),(je||[]).map(t=>e.jsxs(U,{value:t.id,children:[t.plan_name||"Assinatura"," — ",g(Number(t.mrr_amount||0))," (",t.status,")"]},t.id))]})]}),e.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[e.jsx(lt,{checked:ee,disabled:!F,onCheckedChange:t=>ie(!!t)}),e.jsxs("span",{className:"text-sm",children:["Bloquear acesso à base em caso de inadimplência da negociação",e.jsx("span",{className:"block text-xs text-muted-foreground",children:"A fatura gerada entra no cálculo de suspensão da assinatura."})]})]}),ee&&!F&&e.jsx("p",{className:"text-xs text-destructive",children:"Selecione uma assinatura para habilitar o bloqueio."}),qe&&e.jsxs("div",{className:"space-y-2 border-t pt-3",children:[e.jsxs(f,{className:"text-sm font-medium",children:["Split de pagamento (",V.length," CNPJs)"]}),e.jsxs(dt,{value:P,onValueChange:t=>te(t),className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{value:"conjunta",id:"sm-conj"}),e.jsx(f,{htmlFor:"sm-conj",className:"text-sm",children:"Conjunta — uma cobrança única no CNPJ principal"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{value:"individual",id:"sm-ind"}),e.jsx(f,{htmlFor:"sm-ind",className:"text-sm",children:"Individual — uma negociação por CNPJ (rateio proporcional)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{value:"eleito",id:"sm-ele"}),e.jsx(f,{htmlFor:"sm-ele",className:"text-sm",children:"CNPJ eleito — um pagador assume o total"})]})]}),P==="eleito"&&e.jsxs(ut,{value:re,onValueChange:pe,children:[e.jsx(xt,{children:e.jsx(pt,{placeholder:"Escolha o CNPJ pagador"})}),e.jsx(ht,{children:(V||[]).map(t=>{var o,r;return e.jsxs(U,{value:t.target_customer_id,children:[((o=t.customers)==null?void 0:o.company_name)||t.target_customer_id," — ",((r=t.customers)==null?void 0:r.document)||""]},t.target_customer_id)})})]}),P==="individual"&&tt.length>0&&e.jsx("div",{className:"rounded-lg bg-muted/40 p-2 space-y-1",children:tt.map(t=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"truncate mr-2",children:t.name}),e.jsx("span",{className:"font-mono tabular-nums",children:g(t.amount)})]},t.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{className:"text-sm font-medium",children:"Tipo de desconto"}),e.jsxs(dt,{value:le,onValueChange:t=>Ve(t),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{value:"percent",id:"dt-pct"}),e.jsx(f,{htmlFor:"dt-pct",className:"text-sm",children:"Percentual"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{value:"fixed",id:"dt-fix"}),e.jsx(f,{htmlFor:"dt-fix",className:"text-sm",children:"Valor fixo"})]})]})]}),e.jsxs("div",{children:[e.jsx(f,{className:"text-sm font-medium",children:le==="percent"?`Desconto (%) — máx ${Re}%`:"Desconto (R$)"}
1),e.jsx(K,{type:"text",inputMode:"decimal",value:Fe,onChange:t=>{const o=t.target.value;(o===""||/^\d*[.,]?\d*$/.test(o))&&Le(o)},className:"mt-1"}),at&&e.jsx("p",{className:"text-xs text-destructive mt-1",children:Me&&!L?`Desconto de ${oe.toFixed(2)}% acima do teto de ${Qe}% — solicite autorização abaixo.`:`Desconto máximo permitido: ${Re}%`})]}),Me&&e.jsx("div",{className:`rounded-xl border p-3 space-y-2 ${L?"border-emerald-500/40 bg-emerald-500/10":"border-amber-500/40 bg-amber-500/10"}`,children:L?e.jsxs("p",{className:"text-sm text-emerald-700 dark:text-emerald-400",children:["Desconto de ",oe.toFixed(2),"% autorizado (limite até ",Number(L.discount_percent??0).toFixed(2),"%). Pode emitir."]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm text-amber-700 dark:text-amber-400",children:["Desconto de ",oe.toFixed(2),"% excede o teto de ",$e,"% e exige autorização antes da emissão."]}),e.jsx(Oe,{placeholder:"Justifique o desconto solicitado",value:st,onChange:t=>Ut(t.target.value),className:"bg-background"}),e.jsx(j,{size:"sm",disabled:st.trim().length<10||Ft.isPending,onClick:()=>Ft.mutate({customer_id:u,invoice_ids:A,original_total:W,discount_percent:Number(oe.toFixed(4)),discount_amount:Ne,installments:D,threshold_percent:$e,justificativa:st.trim()}),children:"Solicitar autorização"})]})}),e.jsxs("div",{children:[e.jsx(f,{className:"text-sm font-medium",children:O?"Parcelamento — sem cartão liberado o pagamento é à vista":`Máximo de parcelas no cartão (limite ${Te} — até ${He}x sem juros)`}),e.jsx(K,{type:"text",inputMode:"numeric",value:O?"1":J,disabled:O,onChange:t=>{const o=t.target.value;(o===""||/^\d*$/.test(o))&&De(o)},className:"mt-1"}),O?e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"PIX e boleto são sempre à vista — libere o cartão para permitir parcelamento."}):e.jsxs(e.Fragment,{children:[Q.hasInterest&&e.jsxs("p",{className:"text-xs text-amber-600 dark:text-amber-400 mt-1",children:["Acima de ",He,"x: juros de ",Xe,"% a.m. repassados ao cliente."]}),!Q.hasInterest&&D>1&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[D,"x sem juros"]}),nt&&e.jsxs("p",{className:"text-xs text-destructive mt-1",children:["Parcela mínima: ",g(Ue)]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{className:"text-sm font-medium",children:"Formas de pagamento liberadas ao cliente"}),e.jsx("div",{className:"flex flex-wrap gap-4",children:[{key:"pix",label:"PIX (à vista)"},{key:"boleto",label:"Boleto (Pagar.me, à vista)"},{key:"cartao",label:"Cartão de crédito (parcelável)"}].map(t=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{id:`pm-${t.key}`,checked:M.has(t.key),onCheckedChange:o=>{ce(r=>{const m=new Set(r);return o?m.add(t.key):m.delete(t.key),m.has("cartao")||De("1"),m})}}),e.jsx(f,{htmlFor:`pm-${t.key}`,className:"text-sm",children:t.label})]},t.key))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"O cliente recebe um único link do portal e escolhe entre as formas liberadas."}),it&&e.jsx("p",{className:"text-xs text-destructive",children:"Selecione ao menos uma forma de pagamento."})]}),et&&e.jsxs("div",{children:[e.jsx(f,{className:"text-sm font-medium",children:"Data de vencimento do boleto"}),e.jsx(K,{type:"date",value:ae,onChange:t=>B(t.target.value),className:"mt-1",min:new Date().toISOString().split("T")[0]}),ot&&ae===""&&e.jsx("p",{className:"text-xs text-destructive mt-1",children:"Informe a data de vencimento"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{className:"text-sm font-medium",children:"Nota fiscal do valor total da renegociação"}),ve?e.jsxs("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ya,{className:"h-4 w-4 text-amber-500 mt-0.5 shrink-0"}),e.jsx("p",{className:"text-sm text-foreground",children:Ee.length===1?"Uma fatura selecionada já possui NFS-e emitida — a nota não será emitida novamente para evitar duplicidade fiscal:":`${Ee.length} faturas selecionadas já possuem NFS-e emitida — a nota não será emitida novamente para evitar duplicidade fiscal:`})]}),e.jsx("ul",{className:"text-xs text-muted-foreground pl-6 list-disc",children:Ee.map(t=>e.jsxs("li",{children:[t.invoice_number||t.id.slice(0,8),t.nfse_numero?` — NFS-e nº ${t.nfse_numero}`:""]},t.id))}),e.jsxs("p",{className:"text-xs text-muted-foreground pl-6",children:["Esta renegociação seguirá com ",e.jsx("span",{className:"font-medium",children:"Não emitir"}),"."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(dt,{value:z,onValueChange:t=>se(t),className:"flex flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{value:"antecipada",id:"nf-antes"}),e.jsx(f,{htmlFor:"nf-antes",className:"text-sm",children:"Emitir junto com a cobrança"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{value:"apos_pagamento",id:"nf-apos"}),e.jsx(f,{htmlFor:"nf-apos",className:"text-sm",children:"Emitir após o pagamento"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{value:"nao_emitir",id:"nf-nao"}),e.jsx(f,{htmlFor:"nf-nao",className:"text-sm",children:"Não emitir"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:z==="nao_emitir"?"Nenhuma nota será emitida para esta renegociação.":z==="antecipada"?"A NFS-e do valor total sai junto com a cobrança (boleto, PIX ou cartão), antes do pagamento.":"A NFS-e do valor total será emitida quando o pagamento for confirmado."}),z!=="nao_emitir"&&e.jsxs("div",{className:"space-y-1 pt-1",children:[e.jsx(f,{className:"text-sm font-medium",children:"Descrição da nota fiscal"}),e.jsx(Oe,{rows:3,value:q||Ge,maxLength:Ce,onChange:t=>Pe(t.target.value),placeholder:Ge,className:"text-sm"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Texto que aparece na discriminação da nota. Editável."}),e.jsxs("span",{className:`text-xs tabular-nums ${We.length>=Ce?"text-destructive":"text-muted-foreground"}`,children:[We.length,"/",Ce]})]})]})]})]}),e.jsxs("div",{children:[e.jsx(f,{className:"text-sm font-medium",children:"Observações (opcional)"}
1),e.jsx(K,{value:he,onChange:t=>Ke(t.target.value),className:"mt-1",placeholder:"Motivo da renegociação..."})]}),e.jsxs("div",{className:"rounded-xl border p-4 space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground text-sm",children:"Resumo"}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Original"}),e.jsx("span",{className:"font-mono tabular-nums",children:g(W)})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Desconto"}),e.jsxs("span",{className:"text-emerald-600 dark:text-emerald-400 font-mono tabular-nums",children:["-",g(Ne)]})]}),e.jsxs("div",{className:"flex justify-between text-sm font-bold border-t pt-2",children:[e.jsx("span",{children:"Total à vista"}),e.jsx("span",{className:"font-mono tabular-nums",children:g(_e)})]}),O?e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Formas liberadas"}),e.jsxs("span",{children:[Array.from(M).join(", ")||"—"," (à vista)"]})]}):D>1&&e.jsxs(e.Fragment,{children:[Q.hasInterest&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Juros (",Xe,"% a.m.)"]}),e.jsxs("span",{className:"text-amber-600 dark:text-amber-400 font-mono tabular-nums",children:["+",g(Q.interestAmount)]})]}),e.jsxs("div",{className:"flex justify-between text-sm font-bold",children:[e.jsx("span",{children:"Total financiado"}),e.jsx("span",{className:"font-mono tabular-nums",children:g(Q.financedTotal)})]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Parcelas"}),e.jsxs("span",{className:"font-mono tabular-nums",children:[D,"x ",g(St),Q.hasInterest?"":" (sem juros)"]})]}),Q.hasInterest&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:"Parcelamento com juros repassados ao cliente."})]})]})]}),l===3&&ne.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(mt,{className:"h-8 w-8 text-primary"})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:ne.length>1?`${ne.length} renegociações criadas (uma por CNPJ do split)`:"Renegociação criada com sucesso"})]}),ne.map(t=>e.jsxs("div",{className:"rounded-xl border p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-foreground font-mono",children:t.negotiation_number}),t.company&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t.company})]}),e.jsx("span",{className:"font-mono tabular-nums text-sm",children:g(t.amount)})]}),t.checkout_url&&!t.boleto_url&&e.jsxs("div",{className:"space-y-2 text-left",children:[e.jsx(f,{className:"text-sm font-medium",children:"Link de pagamento (validade: 3 dias)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(K,{readOnly:!0,value:t.checkout_url,className:"font-mono text-xs"}),e.jsx(j,{variant:"outline",size:"icon",onClick:()=>{navigator.clipboard.writeText(t.checkout_url),k({title:"Link copiado"})},children:e.jsx(ct,{className:"h-4 w-4"})})]})]}),t.boleto_url&&e.jsxs("div",{className:"space-y-2 text-left",children:[e.jsx(f,{className:"text-sm font-medium",children:"Boleto gerado"}),e.jsxs(j,{variant:"outline",className:"w-full",onClick:()=>Da(t.boleto_url),children:[e.jsx(ft,{className:"h-4 w-4 mr-2"})," Abrir Boleto PDF"]}),t.boleto_barcode&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(K,{readOnly:!0,value:t.boleto_barcode,className:"font-mono text-xs"}),e.jsx(j,{variant:"outline",size:"icon",onClick:()=>{navigator.clipboard.writeText(t.boleto_barcode),k({title:"Código de barras copiado"})},children:e.jsx(ct,{className:"h-4 w-4"})})]}),t.pix_copy_paste&&e.jsxs("div",{children:[e.jsx(f,{className:"text-sm font-medium",children:"PIX Copia e Cola"}),e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(K,{readOnly:!0,value:t.pix_copy_paste,className:"font-mono text-xs"}),e.jsx(j,{variant:"outline",size:"icon",onClick:()=>{navigator.clipboard.writeText(t.pix_copy_paste),k({title:"PIX copiado"})},children:e.jsx(ct,{className:"h-4 w-4"})})]})]})]}),!t.checkout_url&&!t.boleto_url&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Cobrança não gerada. Verifique os dados cadastrais e reprocesse pela listagem."})]},t.negotiation_number)),e.jsx(j,{onClick:c,className:"w-full",children:"Fechar"})]}),l===2&&$.length>0&&e.jsxs("div",{className:"rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Para criar a renegociação, resolva:"}),e.jsx("ul",{className:"list-disc pl-5 space-y-0.5",children:$.map(t=>e.jsx("li",{children:t},t))})]}),l<3&&e.jsxs(Mt,{className:"flex justify-between sm:justify-between",children:[e.jsxs(j,{variant:"outline",onClick:()=>l===1?c():N(l-1),children:[e.jsx(wa,{className:"h-4 w-4 mr-2"})," ",l===1?"Cancelar":"Voltar"]}),l===1&&e.jsxs(j,{disabled:!Jt,onClick:()=>N(2),children:["Próximo ",e.jsx(Ca,{className:"h-4 w-4 ml-2"})]}),l===2&&e.jsxs(j,{disabled:!Ht||Ae||!v,onClick:Gt,title:$[0],children:[Ae?e.jsx(Bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(mt,{className:"h-4 w-4 mr-2"}),"Criar Renegociação"]})]})]})})}export{Ss as default};

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.