PageSourceSearch

https://distribuidoraeficaz.com.br/assets/CRMDealDetail-BAkXEktX.js

js distribuidoraeficaz.com.br collected 2026-09-30 06:38:23 UTC 69,366 bytes, 7 lines download raw bytes

1import{k as Ns,r as m,b6 as W,j as e,ae as le,ak as ys,Y as N,b7 as ee,B as S,a1 as _,C as U,y as Pe,M as bs,a2 as ke,ai as de,aj as me,aL as ue,aM as xe,aN as qe,_ as ws,l as ts,a0 as Cs,a3 as Ss,L as ze,T as Ke,f as Ve,g as $e,h as Qe}from"./index-DD08oKkH.js";import{P as rs,a as ns,b as is,o as Le,p as ks,A as Ge}from"./AppLayout-D6ubUPnp.js";import{I as F}from"./input-B84uDMhG.js";import{S as V,a as $,b as Q,c as G,d as K}from"./select-Z2lIjOKx.js";import{T as qs,a as Es,b as pe,c as ge}from"./tabs-BQOuVjK6.js";import{B as I}from"./badge-TzaVLEqa.js";import{C as Re}from"./checkbox-B5H1M5uB.js";import{A as ve,a as fe,b as je,c as _e,d as Ne,e as ye,f as be,g as we}from"./alert-dialog-CbrU8xIO.js";import{L as A}from"./label-C_AqT0HT.js";import{A as As,a as Ds}from"./avatar-CuB8ueCH.js";import{C as os,a as ls,b as cs,c as ds,e as ms,d as us}from"./command-DSivP7qb.js";import{g as He}from"./tagColors-D8LSJr7Q.js";import{C as Ue,c as Os,t as Ts}from"./CopyButton-YLBn9baz.js";import{M as xs,S as Ls,n as Rs,E as Ms,b as Is,a as Fs,C as We,u as Bs}from"./ConversaThread-BRQGL1KB.js";import{L as oe}from"./loader-circle-bWaExBdR.js";import{P as Ee}from"./plus-pjMl7Chx.js";import{S as Ps}from"./star-GBDLCk1C.js";import{T as re}from"./trash-2-6vKWPZvl.js";import{S as hs,a as zs,b as Ks,R as Vs,Q as $s}from"./leadOptions-E-zlurAn.js";import{R as Qs}from"./refresh-cw-B5ZA3IHb.js";import{E as Te}from"./external-link-B3r6jir4.js";import{V as Gs}from"./video-BfYRNLs0.js";import{C as Hs}from"./copy-C7AwzVAT.js";import{P as Me}from"./pencil-BeMsXJ8Y.js";import{C as Us}from"./calendar-U9bsgcO-.js";import{M as Ws}from"./mail-mKzfESKC.js";import{f as Ce,p as Se}from"./pt-BR-DuqbTpbj.js";import{T as ce}from"./textarea-Dw2vWDps.js";import{C as Js}from"./circle-check-DzTjcqqN.js";import{M as Xs}from"./message-circle-C-4bdBLM.js";import{T as ps}from"./trophy-kyG7oTme.js";import{C as gs}from"./circle-x-DKoeCUSQ.js";import{R as Ys,a as Je}from"./radio-group-Bx12drIJ.js";import{C as Zs}from"./chevrons-up-down-z7-OpKrk.js";import{C as ea}from"./check-Vq6YUZzP.js";import{T as sa,a as aa,b as Xe,c as se,d as ta,e as ae}from"./table-D2SrVSoK.js";import{u as ra}from"./useMutation-DwezPQ8y.js";import{L as na}from"./link-2-CWmtvSri.js";import{A as ia}from"./arrow-left-B6Um6yVZ.js";import{R as Ye}from"./rotate-ccw-f41oaAje.js";import{U as oa}from"./user-plus-BQ46wlEf.js";import"./separator-DcgB2vcW.js";import"./skeleton-DAquBJh-.js";import"./log-out-CtAHRyRL.js";import"./chart-column-CNzwbOb0.js";import"./book-open-0tveb44T.js";import"./circle-help-Sl1Mi7iN.js";import"./bot-efvonDPE.js";import"./building-2-CN2nDRo0.js";import"./receipt-atrr_QaW.js";import"./trending-down-D3fD_Eq1.js";import"./tags-DddE77Ph.js";import"./clipboard-check-BAME_Mla.js";import"./graduation-cap-96y0_fdT.js";import"./database-CdgJkL4z.js";import"./message-circle-question-CB4989QB.js";import"./file-text-BGF_vpkj.js";import"./send-Hwb5eblX.js";import"./chart-pie-BeJ8Fw_X.js";import"./wallet-FX2dCTJO.js";import"./landmark-DlhgmoqW.js";import"./bell-Fy3CySog.js";import"./target-hgGodHDb.js";import"./purify.es-sOfw8HaZ.js";import"./index-BdQq_4o_.js";import"./index-D_vJpsAk.js";import"./index-BRzcycjs.js";import"./search-Ba6CVHm-.js";import"./triangle-alert-BWf4ZBJA.js";import"./user-check-C4betcmH.js";import"./circle-CbJ5QwxK.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const Ze=Ns("GitMerge",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]]),la=["Meta Ads","Google Ads","Indicação Mercos","LP Mercos","Indicação Interna","Site","Cosméticos","Orgânico","Instagram","Evento Sebrae"],ca=new Set(["Cliente Base","Lead frio","Lead morno","Lead quente","Live Lancamento IA 2026","Live Lançamento IA 2026","Mercos","EVENTO SEBRAE"].map(a=>a.trim().toLowerCase())),es=a=>a.trim().replace(/\s+/g," ");function da({value:a,onChange:n,placeholder:x="Selecionar tag..."}){const[u,o]=m.useState(""),[p,d]=m.useState(!1),{data:l=[]}=W({queryKey:["lead-all-tags"],queryFn:async()=>{const{data:t,error:r}=await N.from("leads").select("tags");if(r)throw r;const y=new Set;
6return(t||[]).forEach(k=>(k.tags||[]).forEach(O=>O&&y.add(O))),Array.from(y)},staleTime:6e4}),v=m.useMemo(()=>{const t=new Map;[...la,...l].forEach(y=>{const k=y.toLowerCase();ca.has(k)||t.has(k)||t.set(k,y)});const r=a.map(y=>y.toLowerCase());return Array.from(t.values()).filter(y=>!r.includes(y.toLowerCase())).sort((y,k)=>y.localeCompare(k))},[l,a]),f=t=>{const r=es(t);r&&(a.some(y=>y.toLowerCase()===r.toLowerCase())||(n([...a,r]),o("")))},w=t=>{n(a.filter(r=>r!==t))},E=t=>{t.key==="Enter"||t.key===","?(t.preventDefault(),u.trim()&&f(u)):t.key==="Backspace"&&!u&&a.length&&w(a[a.length-1])};return e.jsxs(rs,{open:p,onOpenChange:d,children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 min-h-10 rounded-md border border-input bg-background px-2 py-1.5 text-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",children:[a.map(t=>e.jsxs(I,{className:le("gap-1 text-white",He(t)),children:[t,e.jsx("button",{type:"button",onClick:()=>w(t),className:"ml-0.5 rounded-full hover:bg-black/20 p-0.5","aria-label":`Remover ${t}`,children:e.jsx(ys,{className:"h-3 w-3"})})]},t)),e.jsx(ns,{asChild:!0,children:e.jsx("input",{value:u,onChange:t=>{o(t.target.value),p||d(!0)},onFocus:()=>d(!0),onKeyDown:E,placeholder:a.length===0?x:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm"})})]}),e.jsx(is,{className:"w-[280px] p-0",align:"start",onOpenAutoFocus:t=>t.preventDefault(),children:e.jsxs(os,{shouldFilter:!0,children:[e.jsx(ls,{value:u,onValueChange:o,placeholder:"Buscar ou criar tag..."}),e.jsxs(cs,{children:[e.jsx(ds,{children:u.trim()?e.jsxs("button",{type:"button",className:"w-full text-left px-2 py-1.5 text-sm hover:bg-accent rounded",onClick:()=>{f(u),d(!1)},children:["Criar tag ",e.jsxs("span",{className:"font-medium",children:['"',es(u),'"']})]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Digite para buscar ou criar"})}),v.length>0&&e.jsx(ms,{heading:"Tags disponíveis",children:v.map(t=>e.jsxs(us,{value:t,onSelect:()=>{f(t),d(!1)},children:[e.jsx("span",{className:le("inline-block w-2 h-2 rounded-full mr-2",He(t))}),t]},t))})]})]})})]})}const ss=()=>({nome:"",cargo:"",email:"",telefone:"",observacao:"",principal:!1});function ma({leadId:a,currentDealId:n}){const x=ee(),[u,o]=m.useState([]),[p,d]=m.useState(!1),[l,v]=m.useState(!1),[f,w]=m.useState(!1),[E,t]=m.useState(null),[r,y]=m.useState([]),{data:k,isLoading:O}=W({queryKey:["lead-contacts",a],queryFn:async()=>{const{data:i,error:g}=await N.from("lead_contacts").select("*").eq("lead_id",a).order("principal",{ascending:!1}).order("created_at",{ascending:!0});if(g)throw g;return i||[]},enabled:!!a});m.useEffect(()=>{k&&!l&&o(k.length>0?k.map(i=>({id:i.id,nome:i.nome||"",cargo:i.cargo||"",email:i.email||"",telefone:i.telefone||"",observacao:i.observacao||"",principal:!!i.principal})):[{...ss(),principal:!0}])},[k,l]);const b=(i,g)=>{v(!0),o(C=>C.map((B,s)=>s===i?{...B,...g}:B))},L=i=>{v(!0),o(g=>g.map((C,B)=>({...C,principal:B===i})))},z=()=>{v(!0),o(i=>[...i,{...ss(),principal:i.length===0}])},h=i=>{v(!0),o(g=>{const C=g.filter((B,s)=>s!==i);return C.length>0&&!C.some(B=>B.principal)&&(C[0].principal=!0),C})},q=async()=>{var B;const i=u.filter(s=>s.email.trim()||s.telefone.trim());if(i.length===0){_.error("Inclua ao menos um contato com e-mail ou telefone.");return}i.some(s=>s.principal)||(i[0].principal=!0);let g=!1;const C=i.map(s=>s.principal&&!g?(g=!0,s):{...s,principal:!1});d(!0);try{const s=(B=C.find(M=>M.principal))==null?void 0:B.email.trim().toLowerCase();if(s){const{data:M}=await N.from("leads").select("id, name, company").ilike("email",s).neq("id",a).limit(1);if(M&&M.length>0){const P=M[0];if(n){const[{data:ne},{data:Y}]=await Promise.all([N.from("deals").select("id, titulo, valor, status, etapa, updated_at").eq("lead_id",P.id).neq("status","mesclado").is("merged_into_deal_id",null).order("updated_at",{ascending:!1}),N.from("deals").select("id, titulo, valor, status, etapa, updated_at").eq("id",n).maybeSingle()]);if(ne&&ne.length>0&&Y){const Ae={id:Y.id,titulo:Y.titulo,valor:Number(Y.valor||0),status:Y.status,etapa:Y.etapa,lead_name:null,lead_email:s,updated_at:Y.updated_at},De=ne.map(J=>({id:J.id,titulo:J.titulo,valor:Number(J.valor||0),status:J.status,etapa:J.etapa,lead_name:P.name||P.company||null,lead_email:s,updated_at:J.updated_at}));t(Ae),y(De),w(!0),_.message("E-mail já existe em outro negócio — abra a mesclagem",{description:`Duplicado em: ${P.name||P.company||P.id}`}),d(!1);return}}_.error(`E-mail já cadastrado em outro lead: ${P.name||P.company||P.id}. Use outro e-mail ou mescle os leads.`,{duration:8e3}),d(!1);return}}const{error:R}=await N.from("lead_contacts").delete().eq("lead_id",a);if(R)throw R;const D=[...C.map(M=>({lead_id:a,nome:M.nome.trim()||null,cargo:M.cargo.trim()||null,email:M.email.trim()||null,telefone:M.telefone.trim()||null,observacao:M.observacao.trim()||null,principal:M.principal}))].sort((M,P)=>Number(M.principal)-Number(P.principal)),{error:X}=await N.from("lead_contacts").insert(D);if(X)throw X;_.success("Contatos salvos"),v(!1),x.invalidateQueries({queryKey:["lead-contacts",a]}),x.invalidateQueries({queryKey:["deal-lead",a]})}catch(s){const R=String((s==null?void 0:s.message)||"");R.includes("leads_email_lower_unique")?_.error("Este e-mail já está cadastrado em outro lead. Use outro e-mail ou mescle os leads duplicados.",{duration:8e3}):_.error("Falha ao salvar: "+(R||"erro"))}finally{d(!1)}};return O?e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[e.jsx(oe,{className:"h-3 w-3 animate-spin"})," Carregando contatos..."]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(xs,{open:f,onOpenChange:w,sourceDeal:E,candidates:r}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(A,{className:"text-xs",children:"Contatos"}),e.jsxs(S,{type:"button",size:"sm",variant:"ghost",className:"h-7 px-2",onClick:z,children:[e.jsx(Ee,{className:"h-3 w-3 mr-1"})," Adicionar"]})]}),e.jsx("div",{className:"space-y-3",children:u.map((i,g)=>e.jsxs("div",{className:`rounded-md border p-2 space-y-1.5 ${i.principal?"border-primary/60 bg-primary/5":"border-border"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>L(g),className:`inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-full ${i.principal?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/70"}`,title:"Marcar como principal",children:[e.jsx(Ps,{className:`h-3 w-3 ${i.principal?"fill-current":""}`}),i.principal?"Principal":"Tornar principal"]}),u.length>1&&e.jsx(S,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>h(g),children:e.jsx(re,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx(F,{placeholder:"Nome",className:"h-8 text-xs",value:i.nome,onChange:C=>b(g,{nome:C.target.value})}),e.jsx(F,{placeholder:"Cargo",className:"h-8 text-xs",value:i.cargo,onChange:C=>b(g,{cargo:C.target.value})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(F,{placeholder:"E-mail",type:"email",className:"h-8 text-xs",value:i.email,onChange:C=>b(g,{email:C.target.value})}),e.jsx(Ue,{value:i.email,label:"E-mail",size:"xs"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(F,{placeholder:"Telefone",className:"h-8 text-xs",value:i.telefone,onChange:C=>b(g,{telefone:C.target.value})}),e.jsx(Ue,{value:i.telefone,label:"Telefone",size:"xs"})]}),e.jsx(F,{placeholder:"Observação",className:"h-8 text-xs",value:i.observacao,onChange:C=>b(g,{observacao:C.target.value})})]},g))}),l&&e.jsx("div",{className:"flex justify-end",children:e.jsxs(S,{type:"button",size:"sm",onClick:q,disabled:p,children:[p?e.jsx(oe,{className:"h-3 w-3 animate-spin mr-1"}):null,"Salvar contatos"]})})]})}const ua=a=>(a||"?").split(" ").map(n=>n[0]).slice(0,2).join("").toUpperCase(),xa=a=>a==null?"":new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format(Number(a));function ha({leadId:a,lead:n,currentDealId:x}){const u=ee(),[o,p]=m.useState(!1),d=m.useRef(!1),[l,v]=m.useState({name:"",company:"",phone:"",email:"",segmento:"",setor:"",salesforce_quantity:"",regime_tributario:"",qtde_notas_emitidas:"",faturamento_mensal:"",tags:[]});m.useEffect(()=>{n&&!d.current&&(v({name:n.name||"",company:n.company||"",phone:n.phone||"",email:n.email||"",segmento:n.segmento||"",setor:n.setor||"",salesforce_quantity:n.salesforce_quantity||"",regime_tributario:n.regime_tributario||"",qtde_notas_emitidas:n.qtde_notas_emitidas||"",faturamento_mensal:n.faturamento_mensal!=null?String(n.faturamento_mensal):"",tags:Array.isArray(n.tags)?n.tags:[]}),d.current=!0)},[n]),m.useEffect(()=>{d.current=!1},[a]);const f=async(t,r)=>{if((n==null?void 0:n[t])===r)return;const{error:y}=await N.from("leads").update({[t]:r}).eq("id",a);if(y){_.error("Sem permissão para editar lead");return}_.success("Salvo")},w=(t,r)=>f(t,r),E=()=>{const t=l.faturamento_mensal===""?null:Number(l.faturamento_mensal);t!=null&&Number.isNaN(t)||f("faturamento_mensal",t)};return n?e.jsxs(U,{className:"p-4 space-y-4 sticky top-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(As,{className:"h-12 w-12",children:e.jsx(Ds,{className:"bg-primary/10 text-primary",children:ua(l.name)})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold truncate",children:l.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:l.company})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(A,{className:"text-xs",children:"Nome"}),e.jsx(F,{value:l.name,onChange:t=>v({...l,name:t.target.value}),onBlur:()=>w("name",l.name)})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs",children:"Empresa"}),e.jsx(F,{value:l.company,onChange:t=>v({...l,company:t.target.value}),onBlur:()=>w("company",l.company)})]}),e.jsx(ma,{leadId:a,currentDealId:x}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs",children:"Segmento"}),e.jsxs(V,{value:l.segmento||void 0,onValueChange:t=>{v({...l,segmento:t}),f("segmento",t)},children:[e.jsx($,{children:e.jsx(Q,{placeholder:"Selecione"})}),e.jsx(G,{children:hs.map(t=>e.jsx(K,{value:t,children:t},t))})]})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs",children:"Setor"}),e.jsxs(V,{value:l.setor||void 0,onValueChange:t=>{v({...l,setor:t}),f("setor",t)},children:[e.jsx($,{children:e.jsx(Q,{placeholder:"Selecione"})}),e.jsx(G,{children:zs.map(t=>e.jsx(K,{value:t,children:t},t))})]})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs",children:"Qtde vendedores"}),e.jsxs(V,{value:l.salesforce_quantity||void 0,onValueChange:t=>{v({...l,salesforce_quantity:t}),f("salesforce_quantity",t)},children:[e.jsx($,{children:e.jsx(Q,{placeholder:"Selecione"})}),e.jsx(G,{children:Ks.map(t=>e.jsx(K,{value:t,children:t},t))})]})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs",children:"Regime tributário"}),e.jsxs(V,{value:l.regime_tributario||void 0,onValueChange:t=>{v({...l,regime_tributario:t}),f("regime_tributario",t)},children:[e.jsx($,{children:e.jsx(Q,{placeholder:"Selecione"})}),e.jsx(G,{children:Vs.map(t=>e.jsx(K,{value:t,children:t},t))})]})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs",children:"Qtde notas emitidas/mês"}),e.jsxs(V,{value:l.qtde_notas_emitidas||void 0,onValueChange:t=>{v({...l,qtde_notas_emitidas:t}),f("qtde_notas_emitidas",t)},children:[e.jsx($,{children:e.jsx(Q,{placeholder:"Selecione"})}),e.jsx(G,{children:$s.map(t=>e.jsx(K,{value:t,children:t},t))})]})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs",children:"Faturamento mensal"}),e.jsx(F,{type:"number",inputMode:"decimal",value:l.faturamento_mensal,onCh
6ange:t=>v({...l,faturamento_mensal:t.target.value}),onBlur:E,placeholder:"0"}),l.faturamento_mensal&&e.jsx("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:xa(Number(l.faturamento_mensal))})]}),e.jsxs("div",{children:[e.jsx(A,{className:"text-xs",children:"Tags"}),e.jsx(da,{value:l.tags,onChange:t=>{v({...l,tags:t}),f("tags",t)}})]})]}),(n.ultima_conversao||n.origem_lead||n.gclid)&&e.jsxs("div",{className:"border-t pt-3 space-y-2",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-medium",children:"Somente leitura"}),n.origem_lead&&e.jsxs("div",{children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:"Origem do lead"}),e.jsx("div",{className:"text-sm break-words",children:n.origem_lead})]}),n.ultima_conversao&&e.jsxs("div",{children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:"Última conversão"}),e.jsx("div",{className:"text-sm break-words",children:n.ultima_conversao})]}),n.gclid&&e.jsxs("div",{children:[e.jsx(A,{className:"text-xs text-muted-foreground",children:"gclid"}),e.jsx("div",{className:"text-xs break-all font-mono text-muted-foreground",children:n.gclid})]})]}),e.jsx(pa,{lead:n,reprocessing:o,onReprocess:async()=>{p(!0);try{const{error:t}=await N.functions.invoke("enrich-lead",{body:{leadId:a}});if(t)throw t;_.success("Reprocessando com IA..."),setTimeout(()=>{u.invalidateQueries({queryKey:["deal-lead",a]})},1500)}catch(t){_.error("Falha ao reprocessar: "+((t==null?void 0:t.message)||"erro"))}finally{p(!1)}}})]}):e.jsx("div",{className:"text-sm text-muted-foreground p-4",children:"Carregando lead..."})}function pa({lead:a,reprocessing:n,onReprocess:x}){var d,l,v,f;const u=a==null?void 0:a.enrichment_status,o=a==null?void 0:a.enrichment,p=(o==null?void 0:o.confidence)==="alto"?"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300":(o==null?void 0:o.confidence)==="medio"?"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300":"bg-muted text-muted-foreground";return e.jsxs("div",{className:"border-t pt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground font-medium flex items-center gap-1",children:[e.jsx(Pe,{className:"h-3 w-3"})," Insights IA"]}),u&&u!=="pending"&&e.jsxs(S,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-[11px]",onClick:x,disabled:n,children:[n?e.jsx(oe,{className:"h-3 w-3 animate-spin"}):e.jsx(Qs,{className:"h-3 w-3"}),e.jsx("span",{className:"ml-1",children:"Reprocessar"})]})]}),u==="pending"&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(oe,{className:"h-3 w-3 animate-spin"})," Enriquecendo com IA..."]}),u==="skipped"&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Sem dados suficientes (",a.enrichment_error||"e-mail genérico sem empresa",")."]}),u==="failed"&&e.jsxs("div",{className:"text-xs text-destructive break-words",children:["Falhou: ",a.enrichment_error||"erro desconhecido"]}),!u&&e.jsxs(S,{type:"button",variant:"outline",size:"sm",onClick:x,disabled:n,className:"w-full text-xs",children:[n?e.jsx(oe,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(Pe,{className:"h-3 w-3 mr-1"}),"Enriquecer com IA"]}),u==="done"&&o&&e.jsxs("div",{className:"space-y-2 text-xs",children:[o.confidence&&e.jsxs("span",{className:`inline-block text-[10px] px-2 py-0.5 rounded-full ${p}`,children:["Confiança: ",o.confidence]}),o.summary&&e.jsx("p",{className:"text-foreground/90",children:o.summary}),(o.industry||o.company_size||o.region)&&e.jsx("div",{className:"text-muted-foreground",children:[o.industry,o.company_size,o.region].filter(Boolean).join(" · ")}),o.website_guess&&e.jsxs("a",{href:o.website_guess.startsWith("http")?o.website_guess:`https://${o.website_guess}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-primary hover:underline break-all",children:[o.website_guess," ",e.jsx(Te,{className:"h-3 w-3 shrink-0"})]}),Array.isArray(o.likely_tech)&&o.likely_tech.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase text-muted-foreground mb-1",children:"Tecnologias prováveis"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:o.likely_tech.map(w=>e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-muted",children:w}
6,w))})]}),Array.isArray(o.b2b_fit_signals)&&o.b2b_fit_signals.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase text-muted-foreground mb-1",children:"Sinais de fit B2B"}),e.jsx("ul",{className:"list-disc list-inside space-y-0.5 text-foreground/90",children:o.b2b_fit_signals.map((w,E)=>e.jsx("li",{children:w},E))})]}),(((d=o.social)==null?void 0:d.linkedin)||((l=o.social)==null?void 0:l.instagram))&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[((v=o.social)==null?void 0:v.linkedin)&&e.jsxs("a",{href:o.social.linkedin,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["LinkedIn ",e.jsx(Te,{className:"h-3 w-3"})]}),((f=o.social)==null?void 0:f.instagram)&&e.jsxs("a",{href:o.social.instagram,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["Instagram ",e.jsx(Te,{className:"h-3 w-3"})]})]}),o.notes&&e.jsx("div",{className:"text-muted-foreground italic",children:o.notes}),a.enrichment_at&&e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["Atualizado em ",new Date(a.enrichment_at).toLocaleString("pt-BR")]}),e.jsx("div",{className:"text-[10px] text-muted-foreground italic border-t pt-1",children:"Inferido por IA — verifique antes de usar comercialmente."})]})]})}const as={ligacao:ks,reuniao:Us,email:Ws,whatsapp:bs,tarefa:Le};function ga({dealId:a}){const n=ee(),[x,u]=m.useState(!1),[o,p]=m.useState(null),[d,l]=m.useState(null),{data:v=[]}=W({queryKey:["deal-activities",a],queryFn:async()=>{const{data:r,error:y}=await N.from("deal_activities").select("*").eq("deal_id",a).order("data_prevista",{ascending:!1,nullsFirst:!1});if(y)throw y;return r}}),f=async(r,y)=>{const{error:k}=await N.from("deal_activities").update({status:y?"realizada":"agendada",data_realizada:y?new Date().toISOString():null}).eq("id",r);if(k){_.error(k.message);return}n.invalidateQueries({queryKey:["deal-activities",a]}),n.invalidateQueries({queryKey:["deals"]})},w=async()=>{if(!d)return;const r=v.find(k=>k.id===d);if(r!=null&&r.google_event_id)try{await N.functions.invoke("google-calendar-sync",{body:{action:"cancel",origem:"deal_activity",activity_id:r.id,google_event_id:r.google_event_id}})}catch{}const{error:y}=await N.from("deal_activities").delete().eq("id",d);if(y){_.error(y.message);return}_.success("Atividade excluída"),l(null),n.invalidateQueries({queryKey:["deal-activities",a]}),n.invalidateQueries({queryKey:["deals"]})},E=v.filter(r=>r.status==="agendada"),t=v.filter(r=>r.status!=="agendada");return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(S,{size:"sm",onClick:()=>{p(null),u(!0)},children:[e.jsx(Ee,{className:"h-4 w-4 mr-1"})," Nova atividade"]})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2 text-muted-foreground",children:"Programadas"}),E.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhuma atividade programada."}),e.jsx("div",{className:"space-y-2",children:E.map(r=>{const y=as[r.tipo]||Le;return e.jsxs(U,{className:"p-3 flex items-start gap-3",children:[e.jsx(Re,{checked:!1,onCheckedChange:k=>f(r.id,!!k),className:"mt-1"}),e.jsx(y,{className:"h-4 w-4 text-primary mt-1 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium text-sm whitespace-pre-wrap",children:r.descricao||r.titulo}),r.data_prevista&&e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:Ce(new Date(r.data_prevista),"dd/MM/yyyy 'às' HH:mm",{locale:Se})}),r.meet_link&&e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsxs("a",{href:r.meet_link,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Gs,{className:"h-3 w-3"})," Entrar no Google Meet"]}),e.jsx(S,{variant:"ghost",size:"icon",className:"h-6 w-6",title:"Copiar link do Meet",onClick:()=>{navigator.clipboard.writeText(r.meet_link),_.success("Link copiado")},children:e.jsx(Hs,{className:"h-3 w-3"})})]})]}),e.jsxs("div",{className:"flex gap-1 shrink-0",children:[e.jsx(S,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{p(r),u(!0)},title:"Editar",children:e.jsx(Me,{className:"h-3.5 w-3.5"})}),e.jsx(S,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>l(r.id),title:"Excluir",children:e.jsx(re,{className:"h-3.5 w-3.5"})})]})]},r.id)})})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2 text-muted-foreground",children:"Histórico"}),t.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sem histórico."}),e.jsx("div",{className:"space-y-2",children:t.map(r=>{const y=as[r.tipo]||Le;return e.jsxs(U,{className:"p-3 flex items-start gap-3 opacity-75",children:[e.jsx(Re,{checked:!0,onCheckedChange:k=>f(r.id,!!k),className:"mt-1"}),e.jsx(y,{className:"h-4 w-4 mt-1 shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm line-through whitespace-pre-wrap",children:r.descricao||r.titulo}),r.data_realizada&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Realizada em ",Ce(new Date(r.data_realizada),"dd/MM/yyyy",{locale:Se})]})]}),e.jsx(S,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:text-destructive shrink-0",onClick:()=>l(r.id),title:"Excluir",children:e.jsx(re,{className:"h-3.5 w-3.5"})})]},r.id)})})]}),e.jsx(Ls,{open:x,onOpenChange:r=>{u(r),r||p(null)},dealId:a,activity:o}),e.jsx(ve,{open:!!d,onOpenChange:r=>!r&&l(null),children:e.jsxs(fe,{children:[e.jsxs(je,{children:[e.jsx(_e,{children:"Excluir atividade?"}),e.jsx(Ne,{children:"Esta ação não pode ser desfeita."})]}),e.jsxs(ye,{children:[e.jsx(be,{children:"Cancelar"}),e.jsx(we,{onClick:w,children:"Excluir"})]})]})})]})}function va({dealId:a}){const{user:n}=ke(),x=ee(),[u,o]=m.useState(""),[p,d]=m.useState(null),[l,v]=m.useState(""),[f,w]=m.useState(null),{data:E=[]}=W({queryKey:["deal-notes",a],queryFn:async()=>{const{data:b,error:L}=await N.from("deal_notes").select("*").eq("deal_id",a).order("created_at",{ascending:!1});if(L)throw L;return b}}),t=async()=>
6{if(!u.trim())return;const{error:b}=await N.from("deal_notes").insert({deal_id:a,conteudo:u.trim(),created_by:n==null?void 0:n.id});if(b){_.error(b.message);return}o(""),x.invalidateQueries({queryKey:["deal-notes",a]})},r=b=>{d(b.id),v(b.conteudo)},y=()=>{d(null),v("")},k=async()=>{if(!p||!l.trim())return;const{error:b}=await N.from("deal_notes").update({conteudo:l.trim()}).eq("id",p);if(b){_.error(b.message);return}y(),x.invalidateQueries({queryKey:["deal-notes",a]})},O=async()=>{if(!f)return;const{error:b}=await N.from("deal_notes").delete().eq("id",f);if(b){_.error(b.message);return}_.success("Observação excluída"),w(null),x.invalidateQueries({queryKey:["deal-notes",a]})};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{placeholder:"Adicionar uma observação...",value:u,onChange:b=>o(b.target.value),rows:3}),e.jsx("div",{className:"flex justify-end",children:e.jsx(S,{size:"sm",onClick:t,disabled:!u.trim(),children:"Adicionar"})})]}),e.jsxs("div",{className:"space-y-2",children:[E.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sem observações."}),E.map(b=>e.jsx(U,{className:"p-3",children:p===b.id?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{value:l,onChange:L=>v(L.target.value),rows:3,autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(S,{size:"sm",variant:"ghost",onClick:y,children:"Cancelar"}),e.jsx(S,{size:"sm",onClick:k,disabled:!l.trim(),children:"Salvar"})]})]}):e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm whitespace-pre-wrap",children:b.conteudo}),e.jsx("div",{className:"text-xs text-muted-foreground mt-2",children:Ce(new Date(b.created_at),"dd/MM/yyyy 'às' HH:mm",{locale:Se})})]}),e.jsxs("div",{className:"flex gap-1 shrink-0",children:[e.jsx(S,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>r(b),title:"Editar",children:e.jsx(Me,{className:"h-3.5 w-3.5"})}),e.jsx(S,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>w(b.id),title:"Excluir",children:e.jsx(re,{className:"h-3.5 w-3.5"})})]})]})},b.id))]}),e.jsx(ve,{open:!!f,onOpenChange:b=>!b&&w(null),children:e.jsxs(fe,{children:[e.jsxs(je,{children:[e.jsx(_e,{children:"Excluir observação?"}),e.jsx(Ne,{children:"Esta ação não pode ser desfeita."})]}),e.jsxs(ye,{children:[e.jsx(be,{children:"Cancelar"}),e.jsx(we,{onClick:O,children:"Excluir"})]})]})})]})}function fa({dealId:a,deal:n}){const{data:x=[]}=W({queryKey:["deal-activities",a],queryFn:async()=>{const{data:p}=await N.from("deal_activities").select("*").eq("deal_id",a);return p||[]}}),{data:u=[]}=W({queryKey:["deal-notes",a],queryFn:async()=>{const{data:p}=await N.from("deal_notes").select("*").eq("deal_id",a);return p||[]}}),o=[];n!=null&&n.created_at&&o.push({date:n.created_at,icon:Ee,label:"Negócio criado",color:"text-blue-600"});for(const p of x)p.status==="realizada"&&p.data_realizada&&o.push({date:p.data_realizada,icon:Js,label:`Atividade: ${p.titulo}`,color:"text-green-600"});for(const p of u)o.push({date:p.created_at,icon:Xs,label:`Observação: ${p.conteudo.slice(0,80)}${p.conteudo.length>80?"...":""}`,color:"text-muted-foreground"});return n!=null&&n.data_ganho&&o.push({date:n.data_ganho,icon:ps,label:"Negócio ganho 🎉",color:"text-green-700"}),n!=null&&n.data_perdido&&o.push({date:n.data_perdido,icon:gs,label:`Negócio perdido${n.motivo_perda?`: ${n.motivo_perda}`:""}`,color:"text-red-600"}),o.sort((p,d)=>new Date(d.date).getTime()-new Date(p.date).getTime()),e.jsxs("div",{className:"space-y-3",children:[o.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sem eventos."}),o.map((p,d)=>{const l=p.icon;return e.jsxs(U,{className:"p-3 flex items-start gap-3",children:[e.jsx(l,{className:`h-4 w-4 mt-0.5 shrink-0 ${p.color}`}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm",children:p.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ce(new Date(p.date),"dd/MM/yyyy 'às' HH:mm",{locale:Se})})]})]},d)})]})}function ja({open:a,onOpenChange:n,dealId:x,leadId:u}){const{user:o}=ke(),p=ee(),[d,l]=m.useState("new"),[v,f]=m.useState([]),[w,E]=m.useState(""),[t,r]=m.useState(!1),[y,k]=m.useState(null),[O,b]=m.useState(""),[L,z]=m.useState(""),[h,q]=m.useState(""),[i,g]=m.useState(!1);m.useEffect(()=>{a&&(l("new"),E(""),Promise.all([N.from("customers").select("id, nome, cnpj").order("nome").limit(1e3),N.from("leads").select("name, company, email, phone").eq("id",u).maybeSingle()]).then(([s,R])=>{var j,D,X,M;f(s.data||[]),k(R.data),b(((j=R.data)==null?void 0:j.company)||((D=R.data)==null?void 0:D.name)||""),z(((X=R.data)==null?void 0:X.email)||""),q(((M=R.data)==null?void 0:M.phone)||"")}))},[a,u]);const C=v.find(s=>
6s.id===w),B=async()=>{g(!0);let s=w;if(d==="new"){if(!O.trim()){_.error("Nome do cliente obrigatório"),g(!1);return}const{data:j,error:D}=await N.from("customers").insert({nome:O.trim(),email:L.trim()||null,telefone:h.trim()||null,status:"Ativo",created_by:o==null?void 0:o.id,lead_origem_id:u,deal_origem_id:x}).select("id").single();if(D){_.error("Erro ao criar cliente: "+D.message),g(!1);return}s=j.id}else{if(!w){_.error("Selecione um cliente"),g(!1);return}await N.from("customers").update({lead_origem_id:u,deal_origem_id:x}).eq("id",w)}const{error:R}=await N.from("deals").update({status:"ganho",data_ganho:new Date().toISOString(),customer_id:s}).eq("id",x);if(g(!1),R){_.error("Erro: "+R.message);return}_.success("Negócio ganho! Cliente vinculado."),N.functions.invoke("send-google-ads-conversion",{body:{deal_id:x}}).then(({data:j,error:D})=>{if(D){console.error("[google-ads-conversion] invoke error",D);return}(j==null?void 0:j.status)==="enviado"&&_.success("Conversão enviada ao Google Ads"),(j==null?void 0:j.status)==="sem_gclid"&&_.message("Lead sem GCLID — conversão não enviada ao Google Ads")}).catch(j=>console.error("[google-ads-conversion] error",j)),N.functions.invoke("send-meta-ads-conversion",{body:{deal_id:x}}).then(({data:j,error:D})=>{if(D){console.error("[meta-ads-conversion] invoke error",D);return}(j==null?void 0:j.status)==="enviado"&&_.success("Conversão enviada à Meta Ads"),j==null||j.status}).catch(j=>console.error("[meta-ads-conversion] error",j)),p.invalidateQueries({queryKey:["deals"]}),p.invalidateQueries({queryKey:["deal",x]}),n(!1)};return e.jsx(de,{open:a,onOpenChange:n,children:e.jsxs(me,{children:[e.jsx(ue,{children:e.jsx(xe,{children:"Marcar como ganho"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ys,{value:d,onValueChange:s=>l(s),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Je,{value:"new",id:"new"}),e.jsx(A,{htmlFor:"new",children:"Criar novo cliente"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Je,{value:"existing",id:"existing"}),e.jsx(A,{htmlFor:"existing",children:"Vincular a cliente existente"})]})]}),d==="new"?e.jsxs("div",{className:"space-y-3 pl-6",children:[e.jsxs("div",{children:[e.jsx(A,{children:"Nome / Razão Social *"}),e.jsx(F,{value:O,onChange:s=>b(s.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(A,{children:"E-mail"}),e.jsx(F,{value:L,onChange:s=>z(s.target.value)})]}),e.jsxs("div",{children:[e.jsx(A,{children:"Telefone"}),e.jsx(F,{value:h,onChange:s=>q(s.target.value)})]})]})]}):e.jsxs("div",{className:"pl-6",children:[e.jsx(A,{children:"Cliente *"}),e.jsxs(rs,{open:t,onOpenChange:r,children:[e.jsx(ns,{asChild:!0,children:e.jsxs(S,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[C?`${C.nome}${C.cnpj?` — ${C.cnpj}`:""}`:"Selecione...",e.jsx(Zs,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(is,{className:"w-[400px] p-0",align:"start",children:e.jsxs(os,{children:[e.jsx(ls,{placeholder:"Buscar cliente..."}),e.jsxs(cs,{children:[e.jsx(ds,{children:"Nenhum cliente encontrado"}),e.jsx(ms,{children:v.map(s=>e.jsxs(us,{value:`${s.nome} ${s.cnpj||""}`,onSelect:()=>{E(s.id),r(!1)},children:[e.jsx(ea,{className:le("mr-2 h-4 w-4",w===s.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:s.nome}),s.cnpj&&e.jsx("span",{className:"text-xs text-muted-foreground",children:s.cnpj})]})]},s.id))})]})]})})]})]})]}),e.jsxs(qe,{children:[e.jsx(S,{variant:"outline",onClick:()=>n(!1),children:"Cancelar"}),e.jsx(S,{onClick:B,disabled:i,className:"bg-green-600 hover:bg-green-700",children:"Confirmar ganho"})]})]})})}function _a({open:a,onOpenChange:n,dealId:x}){const u=ee(),[o,p]=m.useState([]),[d,l]=m.useState(""),[v,f]=m.useState(""),[w,E]=m.useState(!1);m.useEffect(()=>{a&&(l(""),f(""),N.from("deal_loss_reasons").select("id, nome, grupo").eq("ativo",!0).order("nome").then(({data:r})=>p(r||[])))},[a]);const t=async()=>{if(!d){_.error("Selecione o motivo");return}const r=o.find(k=>k.id===d);E(!0);const{error:y}=await N.from("deals").update({status:"perdido",data_perdido:new Date().toISOString(),motivo_perda:r==null?void 0:r.nome,motivo_perda_grupo:r==null?void 0:r.grupo,motivo_perda_detalhe:v.trim()||null}).eq("id",x);if(E(!1),y){_.error("Erro: "+y.message);return}
6_.success("Negócio marcado como perdido"),u.invalidateQueries({queryKey:["deals"]}),u.invalidateQueries({queryKey:["deal",x]}),n(!1)};return e.jsx(de,{open:a,onOpenChange:n,children:e.jsxs(me,{children:[e.jsx(ue,{children:e.jsx(xe,{children:"Marcar como perdido"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(A,{children:"Motivo *"}),e.jsxs(V,{value:d,onValueChange:l,children:[e.jsx($,{children:e.jsx(Q,{placeholder:"Selecione..."})}),e.jsx(G,{children:o.map(r=>e.jsxs(K,{value:r.id,children:[r.nome,r.grupo?` — ${r.grupo}`:""]},r.id))})]})]}),e.jsxs("div",{children:[e.jsx(A,{children:"Detalhe (opcional)"}),e.jsx(ce,{value:v,onChange:r=>f(r.target.value),rows:3})]})]}),e.jsxs(qe,{children:[e.jsx(S,{variant:"outline",onClick:()=>n(!1),children:"Cancelar"}),e.jsx(S,{variant:"destructive",onClick:t,disabled:w,children:"Confirmar"})]})]})})}function Na({open:a,onOpenChange:n,dealId:x,subscription:u,onSaved:o}){const{user:p}=ke(),d=!!u,[l,v]=m.useState(""),[f,w]=m.useState(""),[E,t]=m.useState("1"),[r,y]=m.useState(""),[k,O]=m.useState("ativo"),[b,L]=m.useState(""),{data:z=[]}=W({queryKey:["products"],queryFn:async()=>{const{data:g,error:C}=await N.from("products").select("*").order("grupo").order("nome");if(C)throw C;return g}});m.useEffect(()=>{u?(v(u.product_id),w(u.versao||""),t(String(u.quantidade)),y(String(u.valor_unitario)),O(u.status),L(u.observacao||"")):(v(""),w(""),t("1"),y(""),O("ativo"),L(""))},[u,a]);const h=z.find(g=>g.id===l);m.useEffect(()=>{!d&&(h==null?void 0:h.valor_base)!=null&&y(String(h.valor_base))},[l,d]);const q=ra({mutationFn:async()=>{const g={deal_id:x,product_id:l,versao:f||null,quantidade:Number(E),valor_unitario:Number(r),status:k,observacao:b||null,updated_by:p.id};if(d){const{error:C}=await N.from("deal_subscriptions").update(g).eq("id",u.id);if(C)throw C}else{const{error:C}=await N.from("deal_subscriptions").insert({...g,created_by:p.id});if(C)throw C}},onSuccess:()=>{_.success(d?"Item atualizado!":"Item adicionado!"),o()},onError:g=>_.error(g.message)}),i=(Number(E)||0)*(Number(r)||0);return e.jsx(de,{open:a,onOpenChange:n,children:e.jsxs(me,{className:"max-w-md",children:[e.jsx(ue,{children:e.jsx(xe,{children:d?"Editar item do orçamento":"Adicionar produto ao orçamento"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(A,{children:"Produto *"}),e.jsxs(V,{value:l,onValueChange:v,children:[e.jsx($,{children:e.jsx(Q,{placeholder:"Selecione..."})}),e.jsx(G,{children:z.map(g=>e.jsxs(K,{value:g.id,children:[g.nome," (",g.grupo,")"]},g.id))})]})]}),e.jsxs("div",{className:"space-y-1 w-24",children:[e.jsx(A,{children:"Versão"}),e.jsx(F,{value:f,onChange:g=>w(g.target.value),placeholder:"Ex: 2026"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(A,{children:"Quantidade"}),e.jsx(F,{type:"number",min:"1",value:E,onChange:g=>t(g.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(A,{children:"Valor Unitário (R$)"}),e.jsx(F,{type:"number",step:"0.01",value:r,onChange:g=>y(g.target.value)})]})]}),e.jsxs("div",{className:"text-right text-sm text-muted-foreground",children:["Total: ",e.jsx("span",{className:"font-semibold text-foreground",children:i.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(A,{children:"Status"}),e.jsxs(V,{value:k,onValueChange:O,children:[e.jsx($,{children:e.jsx(Q,{})}),e.jsxs(G,{children:[e.jsx(K,{value:"ativo",children:"Ativo"}),e.jsx(K,{value:"inativo",children:"Inativo"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(A,{children:"Observação"}),e.jsx(ce,{value:b,onChange:g=>L(g.target.value),rows:2})]})]}),e.jsx(qe,{children:e.jsx(S,{onClick:()=>q.mutate(),disabled:!l||q.isPending,children:q.isPending?"Salvando...":"Salvar"})})]})})}const te=a=>(a||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"});function ya({deal:a,onChanged:n}){const x=ee(),[u,o]=m.useState(!1),[p,d]=m.useState(null),[l,v]=m.useState(!1),f=a.status!=="aberto",w=!!a.orcamento_snapshot,{data:E=[],refetch:t}=W({queryKey:["deal-subscriptions",a.id],queryFn:async()=>{const{data:h,error:q}=await N.from("deal_subscriptions").select("*, products(nome, grupo)").eq("deal_id",a.id).order("created_at");if(q)throw q;return h}}),r=async(h,q)=>{const{error:i}=await N.from("deals").update({[h]:q}).eq("id",a.id);if(i)return _.error(i.message);x.invalidateQueries({queryKey:["deal",a.id]}),n()},y=async h=>{if(!confirm("Remover este item do orçamento?"))return;const{error:q}=await N.from("deal_subscriptions").delete().eq("id",h);if(q)return _.error(q.message);t()},k=async()=>{const h=window.location.origin;let q=a.fechamento_token;if(!q){q=crypto.randomUUID();const{error:g}=await N.from("deals").update({fechamento_token:q,fechamento_token_at:new Date().toISOString(),fechamento_status:a.fechamento_status||"link_enviado"}).eq("id",a.id);if(g)return _.error(g.message);x.invalidateQueries({queryKey:["deal",a.id]}),n()}const i=`${h}/fechamento/${q}`;await navigator.clipboard.writeText(i),_.success("Link copiado para a área de transferência",{description:i})},O=f&&w?a.orcamento_snapshot.items||[]:E.map(h=>{var q;return{product_id:h.product_id,product_nome:(q=h.products)==null?void 0:q.nome,versao:h.versao,quantidade:Number(h.quantidade),valor_unitario:Number(h.valor_unitario),valor_total:Number(h.valor_total||h.quantidade*h.valor_unitario),status:h.status,observacao:h.observacao,_id:h.id}}),b=Number(f&&w?a.orcamento_snapshot.valor_implantacao||0:a.valor_implantacao||0),L=f&&w?a.orcamento_snapshot.observacoes||"":a.observacoes_orcamento||"",z=O.filter(h=>h.status==="ativo").reduce((h,q)=>h+Number(q.valor_total||0),0);return e.jsxs("div",{className:"space-y-4",children:[w&&e.jsxs(U,{className:"p-3 bg-muted/50 text-sm flex items-center justify-between",children:[e.jsxs("span",{children:["📸 Orçamento congelado em"," ",e.jsx("strong",{children:new Date(a.orcamento_snapshot_at).toLocaleStr
6ing("pt-BR")})]}),a.fechamento_status==="dados_recebidos"&&e.jsx(I,{className:"bg-emerald-600",children:"Dados de fechamento recebidos"})]}),e.jsxs(U,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Valor de implantação"}),e.jsx(F,{type:"text",inputMode:"decimal",defaultValue:te(b),disabled:f,onFocus:h=>{h.target.value=String(b||"")},onBlur:h=>{const q=h.target.value.replace(/[^\d,.-]/g,"").replace(/\./g,"").replace(",","."),i=Number(q)||0;i!==Number(a.valor_implantacao||0)&&r("valor_implantacao",i),h.target.value=te(i)}},`vimpl-${b}`)]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Observações comerciais"}),e.jsx(ce,{defaultValue:L,disabled:f,rows:2,onBlur:h=>{h.target.value!==(a.observacoes_orcamento||"")&&r("observacoes_orcamento",h.target.value||null)}})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-sm border-t pt-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"MRR"}),e.jsxs("div",{className:"text-lg font-semibold",children:[te(z),"/mês"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Implantação"}),e.jsx("div",{className:"text-lg font-semibold",children:te(b)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-muted-foreground",children:"Total inicial"}),e.jsx("div",{className:"text-lg font-semibold text-primary",children:te(z+b)})]})]})]}),e.jsxs(U,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"font-semibold",children:"Assinaturas orçadas"}),!f&&e.jsxs(S,{size:"sm",onClick:()=>{d(null),o(!0)},children:[e.jsx(Ee,{className:"h-4 w-4 mr-1"})," Adicionar produto"]})]}),O.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Nenhum produto orçado."}):e.jsxs(sa,{children:[e.jsx(aa,{children:e.jsxs(Xe,{children:[e.jsx(se,{children:"Produto"}),e.jsx(se,{children:"Versão"}),e.jsx(se,{className:"text-right",children:"Qtd"}),e.jsx(se,{className:"text-right",children:"Valor unit."}),e.jsx(se,{className:"text-right",children:"Total"}),e.jsx(se,{children:"Status"}),!f&&e.jsx(se,{})]})}),e.jsx(ta,{children:O.map((h,q)=>e.jsxs(Xe,{children:[e.jsx(ae,{children:h.product_nome||"—"}),e.jsx(ae,{children:h.versao||"—"}),e.jsx(ae,{className:"text-right",children:h.quantidade}),e.jsx(ae,{className:"text-right",children:te(h.valor_unitario)}),e.jsx(ae,{className:"text-right font-medium",children:te(h.valor_total)}),e.jsx(ae,{children:e.jsx(I,{variant:h.status==="ativo"?"default":"secondary",children:h.status})}),!f&&e.jsx(ae,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsx(S,{size:"icon",variant:"ghost",onClick:()=>{d(E.find(i=>i.id===h._id)),o(!0)},children:e.jsx(Me,{className:"h-4 w-4"})}),e.jsx(S,{size:"icon",variant:"ghost",onClick:()=>y(h._id),children:e.jsx(re,{className:"h-4 w-4 text-destructive"})})]})})]},h._id||q))})]})]}),!f&&e.jsxs("div",{className:"flex justify-end gap-2",children:[a.fechamento_status==="dados_recebidos"&&e.jsxs(S,{variant:"outline",onClick:()=>v(!0),children:[e.jsx(ws,{className:"h-4 w-4 mr-1"})," Ver dados recebidos"]}),e.jsxs(S,{onClick:k,children:[e.jsx(na,{className:"h-4 w-4 mr-1"}),a.fechamento_token?"Copiar link de fechamento":"Gerar link para fechamento"]})]}),e.jsx(Na,{open:u,onOpenChange:o,dealId:a.id,subscription:p,onSaved:()=>{o(!1),t()}}),e.jsx(de,{open:l,onOpenChange:v,children:e.jsxs(me,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(ue,{children:e.jsx(xe,{children:"Dados recebidos do cliente"})}),a.fechamento_dados?e.jsx("div",{className:"space-y-2 text-sm",children:e.jsx("pre",{className:"bg-muted p-3 rounded text-xs overflow-x-auto",children:JSON.stringify(a.fechamento_dados,null,2)})}):e.jsx("p",{className:"text-muted-foreground",children:"Nenhum dado recebido ainda."})]})})]})}const ba=["Alimentos e Bebidas","Cosméticos","Higiene e Limpeza","Rações Pet","Outros"],wa=[{value:"super_fit",label:"Super Fit"},{value:"fit",label:"Fit"},{value:"parcial",label:"Parcial"},{value:"fora_icp",label:"Fora do ICP"}];function Ca({open:a,onOpenChange:n,deal:x,onCreated:u}){const{user:o}=ke(),p=ts(),d=x.fechamento_dados||{},l=x.orcamento_snapshot||{},[v,f]=m.useState(""),[w,E]=m.useState(""),[t,r]=m.useState(""),[y,k]=m.useState(new Date().toISOString().slice(0,10)),[O,b]=m.useState(""),[L,z]=m.useState(!1);m.useEffect(()=>{!a||!(x!=null&&x.lead_id)||(async()=>{const{data:i}=await N.from("leads").select("setor, segmento").eq("id",x.lead_id).maybeSingle();i&&(i.setor&&f(i.setor),i.segmento&&E(i.segmento))})()},[a,x==null?void 0:x.lead_id]);const h=(l.items||[]).filter(i=>i.status==="ativo"),q=async()=>{z(!0);try{const{data:i,error:g}=await N.from("customers").insert({nome:d.razao_social,nome_fantasia:d.nome_fantasia||null,cnpj:d.cnpj,email:d.email_financeiro||null,telefone:d.whatsapp_financeiro||null,cep:d.cep||null,endereco:d.endereco||null,bairro:d.bairro||null,cidade:d.cidade||null,uf:d.uf||null,status:"Aguardando 1º pagamento",setor:v||null,segmento:w||null,ambiente:t||null,data_venda:y,icp_score:O||null,valor_implantacao:Number(l.valor_implantacao||0),responsavel_financeiro:d.responsavel_financeiro||null,responsavel_administrativo:d.responsavel_administrativo||null,email_administrativo:d.email_administrativo||null,whatsapp_administrativo:d.whatsapp_administrativo||null,dia_vencimento:d.dia_vencimento??null,observacoes_faturamento:d.observacoes||null,observacoes_comerciais:x.observacoes_orcamento||null,lead_origem_id:x.lead_id,deal_origem_id:x.id,created_by:o.id}).select().single();if(g)throw g;if(h.length>0){const R=h.map(D=>({cliente_id:i.id,product_id:D.product_id,versao:D.versao||null,quantidade:Number(D.quantidade),valor_unitario:Number(D.valor_unitario),status:"ativo",observacao:D.observacao||null,created_by:o.id})),{error:j}=await N.from("subscriptions").insert(R);if(j)throw j}const{data:C,error:B}=await N.from("implementations").insert({cliente_id:i.id,responsavel_id:null,etapa:"KickOff",status_geral:"Aguardando início"}).select().single();if(B)throw B;const s=d.participantes||[];if(s.length>0){const R=s.map(D=>({implementation_id:C.id,nome:D.nome,email:D.email||null,telefone:D.whatsapp||null,observacao:D.observacao||null})),{error:j}=await N.from("implementation_participants").insert(R);if(j)throw j}await N.from("deals").update({customer_criado_id:i.id,fechamento_status:"cliente_criado"}).eq("id",x.id),_.success("Cliente, assinaturas e implantação criados!"),u(i.id),n(!1),p(`/app/clientes/${i.id}`)}catch(i){_.error(i.message)}finally{z(!1)}};return e.jsx(de,{open:a,onOpenChange:n,children:e.jsxs(me,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(ue,{children:e.jsx(xe,{children:"Criar cliente e assinatura"})}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{className:"bg-muted p-3 rounded space-y-1",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Empresa:"})," ",d.razao_social||"—"]}),e.jsxs("div",{children:[e.jsx("strong",{children:"CNPJ:"})," ",d.cnpj||"—"]}
6),e.jsxs("div",{children:[e.jsx("strong",{children:"Itens orçamento:"})," ",h.length]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Implantação:"})," R$ ",Number(l.valor_implantacao||0).toFixed(2)]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Participantes treinamento:"})," ",(d.participantes||[]).length]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(A,{children:"Setor"}),e.jsxs(V,{value:v,onValueChange:f,children:[e.jsx($,{children:e.jsx(Q,{placeholder:"Selecione..."})}),e.jsx(G,{children:ba.map(i=>e.jsx(K,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(A,{children:"Segmento"}),e.jsxs(V,{value:w,onValueChange:E,children:[e.jsx($,{children:e.jsx(Q,{placeholder:"Selecione..."})}),e.jsx(G,{children:hs.map(i=>e.jsx(K,{value:i,children:i},i))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(A,{children:"Ambiente"}),e.jsx(F,{value:t,onChange:i=>r(i.target.value),placeholder:"Ex: Cloud, Local..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(A,{children:"Data da venda"}),e.jsx(F,{type:"date",value:y,onChange:i=>k(i.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(A,{children:"ICP Score"}),e.jsxs(V,{value:O,onValueChange:b,children:[e.jsx($,{children:e.jsx(Q,{placeholder:"—"})}),e.jsx(G,{children:wa.map(i=>e.jsx(K,{value:i.value,children:i.label},i.value))})]})]})]})]}),e.jsxs(qe,{children:[e.jsx(S,{variant:"ghost",onClick:()=>n(!1),children:"Cancelar"}),e.jsx(S,{onClick:q,disabled:L,children:L?"Criando...":"Criar cliente"})]})]})})}const Sa=a=>a.replace(/\D+/g,"");function ka({leadId:a,telefone:n}){const x=n?Sa(n).slice(-8):"",{data:u=[],isLoading:o}=W({queryKey:["deal-conversas",a,x],queryFn:async()=>{const l=new Map;if(a){const{data:v}=await N.from("comercial_conversas").select(We).eq("lead_id",a).order("ultima_mensagem_at",{ascending:!1,nullsFirst:!1});for(const f of v||[])l.set(f.id,f)}if(x.length===8){const{data:v}=await N.from("comercial_conversas").select(We).like("telefone",`%${x}`).order("ultima_mensagem_at",{ascending:!1,nullsFirst:!1});for(const f of v||[])l.set(f.id,f)}return[...l.values()].sort((v,f)=>(f.ultima_mensagem_at||f.created_at).localeCompare(v.ultima_mensagem_at||v.created_at))}}),[p,d]=m.useState(null);return m.useEffect(()=>{u.length>0&&!u.some(l=>l.id===p)&&d(u[0].id)},[u,p]),o?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Carregando conversas..."}):u.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Nenhuma conversa comercial registrada para este lead."}):e.jsxs("div",{className:"space-y-3",children:[u.length>1&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:u.map(l=>e.jsxs("button",{onClick:()=>d(l.id),className:le("rounded-md border px-2 py-1 text-xs flex items-center gap-1.5",p===l.id?"border-primary bg-primary/5":"hover:bg-muted/50"),children:[Rs(l),e.jsx(I,{className:le("text-[10px]",Ms[l.estado]),children:Is[l.estado]})]},l.id))}),p&&e.jsx(Fs,{conversaId:p})]})}const qa=["Qualificado","Contatado","Em Conversa","Demo/Proposta","Fechamento"];function Gt(){const{id:a}=Cs(),n=ts(),x=ee(),[u,o]=m.useState(!1),[p,d]=m.useState(!1),[l,v]=m.useState(!1),[f,w]=m.useState(!1),[E,t]=m.useState(!1),[r,y]=m.useState(!1),[k,O]=m.useState(!1),[b,L]=m.useState(!1),[z,h]=m.useState(!1),[q,i]=m.useState(!1),{isAdmin:g,hasRole:C}=Ss(),B=g||C("comercial"),{data:s,isLoading:R}=W({queryKey:["deal",a],queryFn:async()=>{const{data:c,error:T}=await N.from("deals").select("*").eq("id",a).single();if(T)throw T;return c},enabled:!!a}),{data:j}=W({queryKey:["deal-lead",s==null?void 0:s.lead_id],queryFn:async()=>{const{data:c}=await N.from("leads").select("*").eq("id",s.lead_id).single();return c},enabled:!!(s!=null&&s.lead_id)}),D=Bs(s&&j?[{id:s.id,titulo:s.titulo,valor:Number(s.valor||0),etapa:s.etapa,classificacao:s.classificacao||null,tags:s.tags||null,etapa_updated_at:s.etapa_updated_at,lead:{name:j.name,company:j.company||"",email:j.email}}]:[]),X=s?D.get(s.id)||[]:[],{data:M=[]}=W({queryKey:["crm-users"],queryFn:async()=>{const{data:c}=await N.functions.invoke("list-users");return(c==null?void 0:c.users)||[]}}),P=async(c,T)=>{const{error:Z}=await N.from("deals").update({[c]:T}).eq("id",a);if(Z){_.error(Z.message);return}x.invalidateQueries({queryKey:["deal",a]}),x.invalidateQueries({queryKey:["deals"]}
6)},ne=async()=>{if(!a||!s)return;t(!0);const c=new Date().toLocaleString("pt-BR"),T=s.status==="ganho",Z=[s.motivo_perda,s.motivo_perda_detalhe].filter(Boolean).join(" — "),js=T?"status anterior: ganho":Z?`motivo anterior: ${Z}`:"status anterior: perdido",Fe=`[${T?"reaberto":"reativado"} em ${c} — ${js}]`,_s=s.observacoes?`${s.observacoes}
7${Fe}`:Fe,H={status:"aberto",etapa_updated_at:new Date().toISOString(),observacoes:_s};T?(H.data_ganho=null,H.customer_id=null,H.google_ads_conversion_status=null,H.google_ads_conversion_sent_at=null,H.google_ads_conversion_error=null,H.meta_ads_conversion_status=null,H.meta_ads_conversion_sent_at=null,H.meta_ads_conversion_error=null):(H.data_perdido=null,H.motivo_perda=null,H.motivo_perda_grupo=null,H.motivo_perda_detalhe=null);const{error:Be}=await N.from("deals").update(H).eq("id",a);if(t(!1),Be){_.error(Be.message);return}w(!1),_.success(T?"Negócio reaberto":"Negócio reativado"),x.invalidateQueries({queryKey:["deal",a]}),x.invalidateQueries({queryKey:["deals"]})},Y=async()=>{if(!a)return;L(!0);const{error:c}=await N.from("deals").delete().eq("id",a);if(L(!1),c){_.error(c.message);return}O(!1),_.success("Negócio excluído"),x.invalidateQueries({queryKey:["deals"]}),n("/app/crm")},Ae=async()=>{if(!a)return;h(!0);const{data:c,error:T}=await N.functions.invoke("send-google-ads-conversion",{body:{deal_id:a}});if(h(!1),T){_.error("Falha ao reenviar: "+T.message);return}(c==null?void 0:c.status)==="enviado"?_.success("Conversão enviada ao Google Ads"):(c==null?void 0:c.status)==="sem_gclid"?_.message("Lead sem GCLID — não enviado"):_.error("Erro: "+((c==null?void 0:c.error)||"desconhecido")),x.invalidateQueries({queryKey:["deal",a]})},De=async()=>{if(!a)return;i(!0);const{data:c,error:T}=await N.functions.invoke("send-meta-ads-conversion",{body:{deal_id:a}});if(i(!1),T){_.error("Falha ao reenviar: "+T.message);return}(c==null?void 0:c.status)==="enviado"?_.success("Conversão enviada à Meta Ads"):(c==null?void 0:c.status)==="nao_meta_ads"?_.message("Deal não é de Meta Ads — não enviado"):_.error("Erro: "+((c==null?void 0:c.error)||"desconhecido")),x.invalidateQueries({queryKey:["deal",a]})};if(R||!s)return e.jsx(Ge,{children:e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"Carregando..."})});const J=s.status!=="aberto",Ie=s.status==="mesclado",Oe=j?Os({salesforce_quantity:j.salesforce_quantity,segmento:j.segmento,tags:j.tags,origem_lead:j.origem_lead}).tier:"WARM",he=j!=null&&j.created_at?new Date(j.created_at):null,vs=J?new Date(s.data_ganho||s.data_perdido||s.updated_at):new Date,ie=he?Math.max(0,Math.floor((vs.getTime()-he.getTime())/864e5)):null,fs=ie===null?"—":ie===0?"Hoje":ie===1?"1 dia":`${ie} dias`;return e.jsx(Ge,{children:e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(S,{variant:"ghost",size:"sm",onClick:()=>n("/app/crm"),children:[e.jsx(ia,{className:"h-4 w-4 mr-1"})," Voltar ao funil"]}),e.jsxs("div",{className:"flex gap-2",children:[!Ie&&X.length>0&&e.jsxs(S,{variant:"outline",onClick:()=>y(!0),className:"border-amber-500 text-amber-700 hover:bg-amber-600 hover:text-white hover:border-amber-600 dark:text-amber-400 dark:hover:bg-amber-700 dark:hover:text-white transition-colors",children:[e.jsx(Ze,{className:"h-4 w-4 mr-1"})," Mesclar (",X.length,")"]}),!J&&e.jsxs(e.Fragment,{children:[e.jsxs(S,{onClick:()=>o(!0),className:"bg-green-600 hover:bg-green-700",children:[e.jsx(ps,{className:"h-4 w-4 mr-1"})," Ganho"]}),e.jsxs(S,{onClick:()=>d(!0),variant:"destructive",children:[e.jsx(gs,{className:"h-4 w-4 mr-1"})," Perdido"]})]}),s.status==="ganho"&&e.jsxs(e.Fragment,{children:[e.jsx(I,{className:"bg-green-600",children:"Ganho"}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>w(!0),children:[e.jsx(Ye,{className:"h-4 w-4 mr-1"})," Reabrir negócio"]})]}),s.status==="perdido"&&e.jsxs(e.Fragment,{children:[e.jsx(I,{variant:"destructive",children:"Perdido"}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>w(!0),children:[e.jsx(Ye,{className:"h-4 w-4 mr-1"})," Reativar negócio"]})]}),s.fechamento_dados&&!s.customer_criado_id&&e.jsxs(S,{onClick:()=>v(!0),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(oa,{className:"h-4 w-4 mr-1"})," Criar cliente e assinatura"]}),B&&e.jsxs(S,{variant:"ghost",size:"sm",onClick:()=>O(!0),className:"text-destructive hover:text-destructive hover:bg-destructive/10",title:"Excluir negócio (uso restrito: criado por engano)",children:[e.jsx(re,{className:"h-4 w-4 mr-1"})," Excluir"]})]})]}),Ie&&s.merged_into_deal_id&&e.jsx(U,{className:"p-4 border-amber-300 bg-amber-50 dark:bg-amber-950/20",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ze,{className:"h-4 w-4 text-amber-600"}),e.jsxs("span",{children:["Este negócio foi mesclado em"," ",s.merged_at?new Date(s.merged_at).toLocaleStr
7ing("pt-BR"):"—","."]})]}),e.jsx(ze,{to:`/app/crm/${s.merged_into_deal_id}`,className:"text-sm text-primary hover:underline",children:"Ver negócio destino →"})]})}),e.jsx(U,{className:"p-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Título"}),e.jsx(F,{defaultValue:s.titulo,onBlur:c=>c.target.value!==s.titulo&&P("titulo",c.target.value),className:"font-semibold text-lg"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Valor (R$)"}),e.jsx(F,{type:"number",defaultValue:s.valor,onBlur:c=>Number(c.target.value)!==s.valor&&P("valor",Number(c.target.value))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Etapa"}),e.jsxs(V,{value:s.etapa,onValueChange:c=>P("etapa",c),disabled:J,children:[e.jsx($,{children:e.jsx(Q,{})}),e.jsx(G,{children:qa.map(c=>e.jsx(K,{value:c,children:c},c))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Classificação"}),e.jsx(Ke,{children:e.jsxs(Ve,{children:[e.jsx($e,{asChild:!0,children:e.jsx("div",{className:"h-10 flex items-center",children:e.jsx(I,{className:Ts(Oe),children:Oe==="HOT"?"🔥 Hot":Oe==="WARM"?"☀️ Warm":"❄️ Cold"})})}),e.jsx(Qe,{children:"Calculado a partir do lead"})]})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Tempo no funil"}),e.jsx(Ke,{children:e.jsxs(Ve,{children:[e.jsx($e,{asChild:!0,children:e.jsxs("div",{className:"h-10 flex items-center text-sm font-medium",children:[fs,J&&ie!==null&&e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:"(encerrado)"})]})}),e.jsx(Qe,{children:he?`Lead entrou em ${he.toLocaleDateString("pt-BR")}`:"Data de entrada do lead indisponível"})]})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Closer"}),e.jsxs(V,{value:s.closer_id||"",onValueChange:c=>P("closer_id",c),children:[e.jsx($,{children:e.jsx(Q,{placeholder:"Selecione..."})}),e.jsx(G,{children:M.map(c=>{var T;return e.jsx(K,{value:c.id,children:((T=c.user_metadata)==null?void 0:T.full_name)||c.email},c.id)})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"SDR"}),e.jsxs(V,{value:s.sdr_id||"",onValueChange:c=>P("sdr_id",c),children:[e.jsx($,{children:e.jsx(Q,{placeholder:"Selecione..."})}),e.jsx(G,{children:M.map(c=>{var T;return e.jsx(K,{value:c.id,children:((T=c.user_metadata)==null?void 0:T.full_name)||c.email},c.id)})})]})]}),s.customer_id&&e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Cliente vinculado"}),e.jsx("div",{className:"text-sm",children:e.jsx(ze,{to:`/app/clientes/${s.customer_id}`,className:"text-primary hover:underline",children:"Ver cliente"})})]}),s.motivo_perda&&e.jsxs("div",{className:"md:col-span-4",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Motivo da perda"}),e.jsxs("div",{className:"text-sm",children:[s.motivo_perda,s.motivo_perda_detalhe?` — ${s.motivo_perda_detalhe}`:""]})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs(U,{className:"p-3 md:col-span-3 -mt-2 flex flex-wrap items-center justify-between gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Re,{id:"deal-ia-ativa",checked:s.ia_ativa!==!1,onCheckedChange:async c=>{const T=c===!0,{error:Z}=await N.from("deals").update({ia_ativa:T}).eq("id",s.id);if(Z){_.error("Erro: "+Z.message);return}_.success(T?"IA volta a responder este lead":"Somente pessoas respondem este lead"),x.invalidateQueries({queryKey:["deal",s.id]}),x.invalidateQueries({queryKey:["deals"]})}}),e.jsxs("label",{htmlFor:"deal-ia-ativa",className:"cursor-pointer",children:[e.jsx("span",{className:"font-medium",children:"IA responde este lead"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Desmarcado, as mensagens do WhatsApp ficam sob responsabilidade humana."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:"Primeiro contato por WhatsApp:"}),(()=>{const c=s.primeiro_contato_status;return c==="enviado"?e.jsx(I,{className:"bg-green-600",children:"Enviado"}):c==="pendente"?e.jsx(I,{variant:"secondary",children:"Na fila"}):c==="falhou"?e.jsx(I,{variant:"destructive",children:"Falhou"}):c==="ignorado"?e.jsx(I,{variant:"outline",children:"Ignorado"}):e.jsx(I,{variant:"outline",children:"Não se aplica"})})(),s.primeiro_contato_em&&e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(s.primeiro_contato_em).toLocaleStr
7ing("pt-BR")}),s.primeiro_contato_erro&&e.jsx("span",{className:"text-xs text-destructive truncate max-w-xs",children:s.primeiro_contato_erro})]})]}),s.status==="ganho"&&g&&e.jsxs(U,{className:"p-3 md:col-span-3 -mt-2 flex flex-wrap items-center justify-between gap-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:"Google Ads (conversão offline):"}),(()=>{const c=s.google_ads_conversion_status;return c==="enviado"?e.jsx(I,{className:"bg-green-600",children:"Enviada"}):c==="sem_gclid"?e.jsx(I,{variant:"secondary",children:"Sem GCLID"}):c==="erro"?e.jsx(I,{variant:"destructive",children:"Erro"}):e.jsx(I,{variant:"outline",children:"Não enviada"})})(),s.google_ads_conversion_sent_at&&e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(s.google_ads_conversion_sent_at).toLocaleString("pt-BR")}),s.google_ads_conversion_error&&e.jsx("span",{className:"text-xs text-destructive truncate max-w-md",children:s.google_ads_conversion_error})]}),e.jsx(S,{size:"sm",variant:"outline",onClick:Ae,disabled:z,children:z?"Enviando...":"Reenviar"})]}),s.status==="ganho"&&g&&e.jsxs(U,{className:"p-3 md:col-span-3 -mt-2 flex flex-wrap items-center justify-between gap-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:"Meta Ads (conversão offline):"}),(()=>{const c=s.meta_ads_conversion_status;return c==="enviado"?e.jsx(I,{className:"bg-green-600",children:"Enviada"}):c==="nao_meta_ads"?e.jsx(I,{variant:"secondary",children:"Não é Meta Ads"}):c==="erro"?e.jsx(I,{variant:"destructive",children:"Erro"}):e.jsx(I,{variant:"outline",children:"Não enviada"})})(),s.meta_ads_conversion_sent_at&&e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(s.meta_ads_conversion_sent_at).toLocaleString("pt-BR")}),s.meta_ads_conversion_error&&e.jsx("span",{className:"text-xs text-destructive truncate max-w-md",children:s.meta_ads_conversion_error})]}),e.jsx(S,{size:"sm",variant:"outline",onClick:De,disabled:q,children:q?"Enviando...":"Reenviar"})]}),e.jsx("div",{className:"md:col-span-1",children:e.jsx(ha,{leadId:s.lead_id,lead:j,currentDealId:s.id})}),e.jsx("div",{className:"md:col-span-2",children:e.jsxs(qs,{defaultValue:"activities",children:[e.jsxs(Es,{children:[e.jsx(pe,{value:"activities",children:"Atividades e observações"}),e.jsx(pe,{value:"timeline",children:"Linha do tempo"}),e.jsx(pe,{value:"orcamento",children:"Orçamento"}),e.jsx(pe,{value:"conversas",children:"Conversas"})]}),e.jsxs(ge,{value:"activities",className:"mt-4 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold mb-2 text-muted-foreground",children:"Observações"}),e.jsx(va,{dealId:a})]}),e.jsxs("div",{className:"border-t pt-6",children:[e.jsx("h3",{className:"text-sm font-semibold mb-2 text-muted-foreground",children:"Atividades"}),e.jsx(ga,{dealId:a})]})]}),e.jsx(ge,{value:"timeline",className:"mt-4",children:e.jsx(fa,{dealId:a,deal:s})}),e.jsx(ge,{value:"conversas",className:"mt-4",children:e.jsx(ka,{leadId:s.lead_id,telefone:(j==null?void 0:j.phone)??null})}),e.jsx(ge,{value:"orcamento",className:"mt-4",children:e.jsx(ya,{deal:s,onChanged:()=>x.invalidateQueries({queryKey:["deal",a]})})})]})})]}),e.jsx(ja,{open:u,onOpenChange:o,dealId:a,leadId:s.lead_id}),e.jsx(_a,{open:p,onOpenChange:d,dealId:a}),e.jsx(ve,{open:f,onOpenChange:w,children:e.jsxs(fe,{children:[e.jsxs(je,{children:[e.jsx(_e,{children:s.status==="ganho"?"Reabrir este negócio?":"Reativar este negócio?"}),e.jsx(Ne,{children:s.status==="ganho"?e.jsxs(e.Fragment,{children:["Ele voltará para o funil na etapa atual (",s.etapa,") e deixará de contar nos KPIs de ganho. O status anterior ficará registrado nas observações.",e.jsx("br",{}),e.jsx("br",{}),e.jsx("strong",{children:"Atenção:"})," o cliente e a assinatura já criados a partir deste negócio ",e.jsx("strong",{children:"não"})," serão desfeitos automaticamente — ajuste-os manualmente em Clientes, se necessário."]}):e.jsxs(e.Fragment,{children:["Ele voltará para o funil na etapa atual (",s.etapa,") e os dados de perda serão limpos. O motivo anterior ficará registrado nas observações."]})})]}),e.jsxs(ye,{children:[e.jsx(be,{disabled:E,children:"Cancelar"}),e.jsx(we,{onClick:ne,disabled:E,children:E?s.status==="ganho"?"Reabrindo...":"Reativando...":s.status==="ganho"?"Reabrir":"Reativar"})]})]})}),e.jsx(ve,{open:k,onOpenChange:O,children:e.jsxs(fe,{children:[e.jsxs(je,{children:[e.jsx(_e,{children:"Excluir este negócio permanentemente?"}),e.jsxs(Ne,{children:["Use só para negócios criados por engano. Para negócios reais que não fecharam, marque como ",e.jsx("strong",{children:"Perdido"}
7)," — assim eles continuam contando nas métricas de funil.",e.jsx("br",{}),e.jsx("br",{}),"O lead associado ",e.jsx("strong",{children:"não"})," será excluído."]})]}),e.jsxs(ye,{children:[e.jsx(be,{disabled:b,children:"Cancelar"}),e.jsx(we,{onClick:Y,disabled:b,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:b?"Excluindo...":"Excluir negócio"})]})]})}),e.jsx(Ca,{open:l,onOpenChange:v,deal:s,onCreated:()=>x.invalidateQueries({queryKey:["deal",a]})}),e.jsx(xs,{open:r,onOpenChange:y,sourceDeal:{id:s.id,titulo:s.titulo,valor:Number(s.valor||0),status:s.status,etapa:s.etapa,lead_name:(j==null?void 0:j.name)||null,lead_email:(j==null?void 0:j.email)||null,updated_at:s.etapa_updated_at},candidates:X})]})})}export{Gt 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.