PageSourceSearch

https://mgw-service-desk.lovable.app/assets/_authenticated.companies_._companyId-Bk4XiafA.js

js mgw-service-desk.lovable.app collected 2026-10-03 03:35:18 UTC 31,110 bytes, 5 lines download raw bytes

1import{b as as,f as ts,r as u,g as R,s as f,t as o,K as B,j as e,w as oe,x as le,y as ce,B as l,ai as xs,z as de,h as b,a as Oe,i as ps,k as fs,l as js,m as gs,n as Ve,af as vs,d as ys,e as Z,L as _s,I as U,D as Fe,E as Ae,F as ee,G as h,H as Me,J as x,o as Ns,a9 as ws}from"./index-26Acqbp3.js";import{r as Cs,u as ve,w as bs}from"./xlsx-BojT3SgY.js";import{u as L}from"./useMutation-CJU7Y2Do.js";import{u as rs}from"./useErpCatalog-DfhD_IEH.js";import{i as Es,d as Ss,l as ks,s as qs,r as Ps,U as Fs}from"./team.functions-DqU1Tvhl.js";import{B as C}from"./badge-CI4bhZeT.js";import{C as As}from"./calendar-1weLdvq3.js";import{P as Ms,a as zs,b as $s}from"./popover-DH1b4sT0.js";import{M as He}from"./multi-select-B3GSlOdF.js";import{B as Is}from"./briefcase-Cv9Kjm4I.js";import{R as Ls}from"./rotate-ccw-BPEytpeq.js";import{C as Ts}from"./calendar-CQri6Vtw.js";import{g as Ks,I as Ds}from"./ImpersonateFirstAccessDialog-DAv7g0wR.js";import{D as Je,a as Ge,b as We,c as Xe,e as Ye}from"./dialog-CDAhsRK3.js";import{A as Us}from"./arrow-left-Dp9jI21j.js";import{B as Rs}from"./building-2-0IwEcg5Z.js";import{M as ze}from"./mail-C-FTNDQA.js";import{P as Ze}from"./phone-Bc_-d9sb.js";import{P as es}from"./plus-BiqOG09w.js";import{U as ss}from"./user-CzRgWGEd.js";import{F as Bs}from"./file-text-Dk8-y8LI.js";import{D as Qs}from"./download-CU3fFVej.js";import{E as Os}from"./external-link-qMvpPiy-.js";import{S as Vs}from"./shield-check-BqlXwWFX.js";import{U as Hs}from"./upload-DGkcHvn2.js";import{L as Js}from"./log-in-ps3SHbrm.js";import{U as Gs}from"./user-x-B0ExN7Cx.js";import{d as Ws}from"./differenceInDays-CSw9oGhe.js";import"./addDays-BjJ5zrIp.js";import"./startOfMonth-pZOVVt_Q.js";import"./endOfMonth-BrIsZWUR.js";import"./endOfWeek-ntaF6hmF.js";import"./chevron-left-CH3fSJ03.js";import"./chevron-right-DeCExeeX.js";import"./command-FY4rF7kD.js";import"./index-C7yQ2Noq.js";import"./search-Bcbuh6qz.js";import"./chevrons-up-down-zja5P1nL.js";import"./x-B4mrpJvk.js";import"./key-round-DCLAxRcA.js";import"./copy-BEQWcjKF.js";import"./loader-circle-BcK0I5yx.js";function Xs({companyId:i,initialClientSince:p,initialErps:j,initialDefaultProjectId:A}){const{isAgentOrAdmin:ye,profile:me}=as(),T=ts(),g=me?.company_id,[v,k]=u.useState(p?new Date(p+"T00:00:00"):void 0),[M,Q]=u.useState(j??[]),[z,se]=u.useState([]),[O,q]=u.useState(A??null),V=rs(),ae=V.buildOptions(M);u.useEffect(()=>{k(p?new Date(p+"T00:00:00"):void 0),Q(j??[]),q(A??null)},[p,j,A]);const te=R({queryKey:["projects-catalog",g],enabled:!!g,queryFn:async()=>{const{data:t,error:n}=await f.from("projects").select("id, name, code, active").eq("company_id",g).order("name");if(n)throw new Error(n.message);return t??[]}}),$=R({queryKey:["contracted-solutions",g],enabled:!!g,queryFn:async()=>{const{data:t,error:n}=await f.from("contracted_solutions").select("id, name, active").eq("company_id",g).eq("active",!0).order("name");if(n)throw new Error(n.message);return t??[]}}),E=R({queryKey:["client-solutions",i],queryFn:async()=>{const{data:t,error:n}=await f.from("client_solutions").select("solution_id").eq("client_id",i);if(n)throw new Error(n.message);return(t??[]).map(G=>G.solution_id)}});u.useEffect(()=>{E.data&&se(E.data)},[E.data]);const c=L({mutationFn:async()=>{const{data:t,error:n}=await f.from("companies").update({client_since:v?B(v,"yyyy-MM-dd"):null,erps:M,default_project_id:O}).eq("id",i).select("id");if(n)throw console.error("[ClientCommercial] update companies failed:",n),new Error(n.message);if(!t||t.length===0)throw new Error("Sem permissão para atualizar este cliente (verifique seu perfil).");const G=new Set(E.data??[]),K=new Set(z),w=[...K].filter(y=>!G.has(y)),W=[...G].filter(y=>!K.has(y));if(w.length>0){const{error:y}=await f.from("client_solutions").insert(w.map(X=>({client_id:i,solution_id:X})));if(y)throw console.error("[ClientCommercial] insert client_solutions failed:",y),new Error(`Erro ao vincular soluções: ${y.message}`)}if(W.length>0){const{error:y}=await f.from("client_solutions").delete().eq("client_id",i).in("solution_id",W);if(y)throw console.error("[ClientCommercial] delete client_solutions failed:",y),new Error(`Erro ao desvincular soluções: ${y.message}`)}},onSuccess:()=>
1{o.success("Informações comerciais salvas"),T.invalidateQueries({queryKey:["company",i]}),T.invalidateQueries({queryKey:["client-solutions",i]}),T.invalidateQueries({queryKey:["client-solutions-map"]}),T.invalidateQueries({queryKey:["companies"]})},onError:t=>o.error(t.message)}),S=($.data??[]).filter(t=>t.active||z.includes(t.id)).map(t=>({value:t.id,label:t.active?t.name:`${t.name} (inativa)`})),H=t=>$.data?.find(n=>n.id===t)?.name??t,_e=t=>$.data?.find(n=>n.id===t)?.active??!0,P=ye,Ne=p??"",we=v?B(v,"yyyy-MM-dd"):"",J=t=>[...t].sort().join("|"),Ce=u.useMemo(()=>J(j??[]),[j]),ue=u.useMemo(()=>J(E.data??[]),[E.data]),I=we!==Ne||J(M)!==Ce||J(z)!==ue||(O??"")!==(A??"");u.useEffect(()=>{if(!I)return;const t=n=>{n.preventDefault(),n.returnValue=""};return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[I]);const he=()=>{k(p?new Date(p+"T00:00:00"):void 0),Q(j??[]),se(E.data??[]),q(A??null)};return e.jsxs(oe,{children:[e.jsxs(le,{className:"flex flex-row items-center justify-between gap-2",children:[e.jsxs(ce,{className:"text-base flex items-center gap-2",children:[e.jsx(Is,{className:"h-4 w-4"})," Informações comerciais",P&&I&&e.jsx(C,{variant:"outline",className:"text-[10px] border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",title:"Há alterações ainda não salvas",children:"Não salvo"})]}),P&&e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(l,{size:"sm",variant:"ghost",onClick:he,disabled:!I||c.isPending,children:[e.jsx(Ls,{className:"mr-1 h-4 w-4"})," Descartar"]}),e.jsxs(l,{size:"sm",onClick:()=>c.mutate(),disabled:!I||c.isPending,children:[e.jsx(xs,{className:"mr-1 h-4 w-4"})," Salvar"]})]})]}),e.jsxs(de,{className:"space-y-5",children:[e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{children:"Cliente desde"}),P?e.jsxs(Ms,{children:[e.jsx(zs,{asChild:!0,children:e.jsxs(l,{variant:"outline",className:Oe("w-full justify-start text-left font-normal",!v&&"text-muted-foreground"),children:[e.jsx(Ts,{className:"mr-2 h-4 w-4"}),v?B(v,"dd/MM/yyyy"):"Selecionar data"]})}),e.jsx($s,{className:"w-auto p-0",align:"start",children:e.jsx(As,{mode:"single",selected:v,onSelect:k,initialFocus:!0,className:Oe("p-3 pointer-events-auto")})})]}):e.jsx("p",{className:"text-sm",children:v?B(v,"dd/MM/yyyy"):"—"}),P&&v&&e.jsx(l,{variant:"ghost",size:"sm",onClick:()=>k(void 0),children:"Limpar"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{children:"ERP do cliente"}),P?e.jsx(He,{options:ae,selected:M,onChange:Q,placeholder:V.isLoading?"Carregando ERPs...":"Selecione os ERPs"}):M.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:[...M].sort((t,n)=>t.localeCompare(n,"pt-BR")).map(t=>{const n=V.isErpActive(t);return e.jsx(C,{variant:n?"secondary":"outline",className:n?"":"text-muted-foreground line-through",title:n?void 0:"ERP inativo",children:t},t)})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"—"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{children:"Soluções contratadas"}),P?e.jsx(He,{options:S,selected:z,onChange:se,placeholder:$.isLoading?"Carregando catálogo...":"Selecione as soluções",emptyText:"Nenhuma solução cadastrada. Cadastre em Configurações → Soluções Contratadas."}):z.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:[...z].sort((t,n)=>H(t).localeCompare(H(n),"pt-BR")).map(t=>{const n=_e(t);return e.jsx(C,{variant:n?"secondary":"outline",className:n?"":"text-muted-foreground line-through",title:n?void 0:"Solução inativa",children:H(t)},t)})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"—"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(b,{children:"Projeto padrão"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Projeto usado por padrão ao abrir chamados deste cliente (incluindo e-mails recebidos no suporte)."}),P?e.jsxs(ps,{value:O??"__none__",onValueChange:t=>q(t==="__none__"?null:t),children:[e.jsx(fs,{children:e.jsx(js,{placeholder:te.isLoading?"Carregando projetos...":"Selecione um projeto"})}),e.jsxs(gs,{children:[e.jsx(Ve,{value:"__none__",children:"— Nenhum —"}),(te.data??[]).map(t=>e.jsxs(Ve,{value:t.id,children:[t.name,t.code?` (${t.code})`:"",t.active?"":" · inativo"]},t.id))]})]}
1):e.jsx("p",{className:"text-sm",children:te.data?.find(t=>t.id===O)?.name??"—"})]})]})]})}function Da(){const{companyId:i}=vs({from:"/_authenticated/companies_/$companyId"}),p=ts(),{isAgentOrAdmin:j,profile:A}=as(),ye=rs(),me=ys(),T=A?.company_id,g=R({queryKey:["company",i],queryFn:async()=>{const{data:s,error:a}=await f.from("companies").select("*").eq("id",i).single();if(a)throw new Error(a.message);return s}}),v=R({queryKey:["company-contacts",i],queryFn:async()=>{const{data:s,error:a}=await f.from("company_contacts").select("*").eq("company_id",i).order("is_primary",{ascending:!1}).order("name");if(a)throw new Error(a.message);return s??[]}}),k=R({queryKey:["company-contracts",i,T],enabled:!!T&&!!i,queryFn:async()=>{const{data:s,error:a}=await f.from("support_contracts").select("id, name, client_id, start_date, end_date, value, currency, active, project_id, attachment_url, attachment_filename, attachment_original_url, attachment_original_name, attachment_signed, attachment_signed_filename").eq("client_id",i).eq("active",!0).order("end_date",{ascending:!0,nullsFirst:!1});if(a)throw a;const d=Array.from(new Set((s??[]).map(_=>_.project_id).filter(Boolean))),{data:Y}=d.length?await f.from("projects").select("id, name").in("id",d):{data:[]},xe=new Map;return(Y??[]).forEach(_=>xe.set(_.id,_.name)),{contracts:(s??[]).map(_=>({..._,clientName:g.data?.trade_name||g.data?.name||"—",projectName:_.project_id?xe.get(_.project_id)??"—":"—"})),primaryClientId:i}}});function M(s){if(!s.end_date)return{label:"Ativo",tone:"bg-success/15 text-success"};const a=Ws(new Date(s.end_date),new Date);return a<0?{label:"Vencido",tone:"bg-destructive/15 text-destructive"}:a<=30?{label:"Vencendo",tone:"bg-warning/15 text-warning"}:{label:"Ativo",tone:"bg-success/15 text-success"}}const Q=s=>{me({to:"/contracts",search:{contractId:s,from:`company:${i}`}})},z=async s=>{const a=s.attachment_url||s.attachment_original_url;if(!a){o.error("Este contrato não possui documento anexado.");return}const{data:d,error:Y}=await f.storage.from("contract-attachments").createSignedUrl(a,60,{download:s.attachment_signed_filename||s.attachment_filename||s.attachment_original_name||`${s.name}.pdf`});if(Y||!d?.signedUrl){o.error("Não foi possível gerar o link de download.");return}window.open(d.signedUrl,"_blank")},se=()=>{const s=k.data?.primaryClientId??void 0;me({to:"/contracts",search:{new:!0,...s?{clientId:s}:{},from:`company:${i}`}})},[O,q]=u.useState(!1),[V,ae]=u.useState(""),[te,$]=u.useState(!1);u.useEffect(()=>{ae(g.data?.nickname??"")},[g.data]);const E=L({mutationFn:async()=>{const s=V.trim(),{error:a}=await f.from("companies").update({nickname:s||null}).eq("id",i);if(a)throw new Error(a.message)},onSuccess:()=>{o.success("Apelido atualizado"),$(!1),p.invalidateQueries({queryKey:["company",i]}),p.invalidateQueries({queryKey:["companies"]})},onError:s=>o.error(s.message)}),[c,S]=u.useState({id:void 0,name:"",role:"",email:"",phone:"",is_primary:!1}),H=Z(Es),_e=Z(Ss),P=Z(ks),Ne=Z(qs),we=Z(Ps),J=Z(Ks),[Ce,ue]=u.useState(null),[I,he]=u.useState(null),t=async(s,a)=>{if(!s){o.error("Usuário sem e-mail cadastrado");return}if(confirm(`Entrar no Portal do Cliente como "${a||s}"?
2
3Se o usuário ainda não fez o 1º acesso, o sistema gerará uma senha temporária para simular o fluxo de troca de senha; ao encerrar o teste a senha é descartada e o status de 1º acesso é preservado.
4
5Caso contrário, um link mágico será aberto em nova aba (a sessão de admin desta janela será substituída — use janela anônima para preservá-la).`)){ue(s);try{const d=await J({data:{email:s,companyId:i,name:a??void 0}});d.mode==="first_access"?he({email:d.email,name:d.name,tempPassword:d.tempPassword,portalLoginUrl:d.portalLoginUrl,portalHome:d.portalHome}):window.open(d.url,"_blank","noopener,noreferrer")?o.success(`Abrindo portal como ${d.email}`):o.error("Popup bloqueado. Permita popups e tente novamente.")}catch(d){o.error(d?.message??"Falha ao gerar link de acesso")}finally{ue(null)}}},n=R({queryKey:["client-users",i],enabled:j,queryFn:async()=>(await P({data:{client_company_id:i}}))?.users??[]}),[G,K]=u.useState(!1),[w,W]=u.useState({full_name:"",email:""}),y=L({mutationFn:async()=>{const s=await H({data:{full_name:w.full_name.trim(),email:w.email.trim(),role:"requester",client_company_id:i}});if(!s?.success)throw new Error("Convite não foi gravado no backend");return s},onSuccess:()=>{o.success("Convite enviado. O usuário receberá um e-mail para definir a senha."),K(!1),W({full_name:"",email:""}),p.invalidateQueries({queryKey:["client-users",i]})},onError:s=>o.error(s.message)}),X=u.useRef(null),[be,$e]=u.useState(!1),ns=()=>{const s=ve.aoa_to_sheet([["apelido_empresa","nome","email"],["Gentil","João da Silva","[email protected]"],["Kuehne Nagel","Maria Souza","[email protected]"]]),a=ve.book_new();ve.book_append_sheet(a,s,"Usuários"),bs(a,"modelo-usuarios.xlsx")},is=async s=>{$e(!0);try{const a=await s.arrayBuffer(),d=Cs(a,{type:"array"}),Y=d.Sheets[d.SheetNames[0]],xe=ve.sheet_to_json(Y,{defval:""}),_=m=>String(m??"").trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\s_-]/g,""),pe=[];if(xe.forEach((m,N)=>{const F=Object.keys(m),re=F.find(ie=>["nome","name","fullname","nomecompleto"].includes(_(ie))),Be=F.find(ie=>["email","emailaddress"].includes(_(ie))),Qe=F.find(ie=>["apelido","apelidoempresa","empresa","nickname","cliente","tradename","nomefantasia"].includes(_(ie))),je=re?String(m[re]??"").trim():"",ne=Be?String(m[Be]??"").trim().toLowerCase():"",ge=Qe?String(m[Qe]??"").trim():"",hs=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ne);je&&ne&&ge&&hs?pe.push({apelido:ge,full_name:je,email:ne,rowNum:N+2}):(je||ne||ge)&&console.warn(`Linha ${N+2} ignorada: dados inválidos`,{full_name:je,email:ne,apelido:ge})}),pe.length===0){o.error("Nenhuma linha válida. Use colunas 'apelido_empresa', 'nome' e 'email'.");return}const Te=A?.company_id;if(!Te){o.error("Tenant não identificado");return}const{data:ds,error:Ke}=await f.from("companies").select("id, nickname, trade_name, name").eq("tenant_company_id",Te);if(Ke)throw new Error(Ke.message);const Se=new Map;
5(ds??[]).forEach(m=>{[m.nickname,m.trade_name,m.name].forEach(N=>{if(N){const F=_(N);Se.has(F)||Se.set(F,m.id)}})});let ke=0;const D=[],qe=new Set;let Pe=0;const De=pe.length,Ue=o.loading(`Importando 0/${De}...`),fe=[];for(const m of pe){const N=Se.get(_(m.apelido));if(!N){D.push(`Linha ${m.rowNum} (${m.email}): empresa "${m.apelido}" não encontrada`),Pe++;continue}fe.push({row:m,cid:N})}const ms=4;let Re=0;const us=async()=>{for(;Re<fe.length;){const m=Re++,{row:N,cid:F}=fe[m];try{if(!(await H({data:{full_name:N.full_name,email:N.email,role:"requester",client_company_id:F}}))?.success)throw new Error("Falha ao convidar");ke++,qe.add(F)}catch(re){D.push(`Linha ${N.rowNum} (${N.email}): ${re?.message??"erro"}`)}finally{Pe++,o.loading(`Importando ${Pe}/${De}...`,{id:Ue})}}};await Promise.all(Array.from({length:Math.min(ms,fe.length)},us)),qe.forEach(m=>p.invalidateQueries({queryKey:["client-users",m]})),o.dismiss(Ue),ke>0&&o.success(`${ke} usuário(s) convidado(s) em ${qe.size} empresa(s).`),D.length>0&&(o.error(`${D.length} falha(s): ${D.slice(0,3).join("; ")}${D.length>3?"...":""}`),console.warn("[import-users] erros:",D))}catch(a){o.error(a?.message??"Erro ao ler planilha")}finally{$e(!1),X.current&&(X.current.value="")}},os=L({mutationFn:async s=>_e({data:{user_id:s}}),onSuccess:()=>{o.success("Acesso removido"),p.invalidateQueries({queryKey:["client-users",i]})},onError:s=>o.error(s.message)}),ls=L({mutationFn:async({user_id:s,active:a})=>Ne({data:{user_id:s,active:a}}),onSuccess:(s,a)=>{o.success(a.active?"Usuário ativado":"Usuário inativado"),p.invalidateQueries({queryKey:["client-users",i]})},onError:s=>o.error(s.message)}),Ie=L({mutationFn:async s=>we({data:{user_id:s}}),onSuccess:()=>o.success("Convite reenviado"),onError:s=>o.error(s.message)}),Le=L({mutationFn:async()=>{const s={company_id:i,name:c.name.trim(),role:c.role||null,email:c.email||null,phone:c.phone||null,is_primary:c.is_primary};if(c.is_primary&&await f.from("company_contacts").update({is_primary:!1}).eq("company_id",i).eq("is_primary",!0),c.id){const{error:a}=await f.from("company_contacts").update(s).eq("id",c.id);if(a)throw new Error(a.message)}else{const{error:a}=await f.from("company_contacts").insert(s);if(a)throw new Error(a.message)}},onSuccess:()=>{o.success("Contato salvo"),q(!1),S({id:void 0,name:"",role:"",email:"",phone:"",is_primary:!1}),p.invalidateQueries({queryKey:["company-contacts",i]})},onError:s=>o.error(s.message)}),cs=L({mutationFn:async s=>{const{error:a}=await f.from("company_contacts").delete().eq("id",s);if(a)throw new Error(a.message)},onSuccess:()=>{o.success("Contato removido"),p.invalidateQueries({queryKey:["company-contacts",i]})},onError:s=>o.error(s.message)});if(g.isLoading)return e.jsx("p",{className:"p-6 text-sm text-muted-foreground",children:"Carregando..."});if(!g.data)return e.jsx("p",{className:"p-6 text-sm",children:"Empresa não encontrada."});const r=g.data,Ee=v.data??[];return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(l,{asChild:!0,variant:"ghost",size:"sm",children:e.jsxs(_s,{to:"/companies",children:[e.jsx(Us,{className:"mr-1 h-4 w-4"})," Voltar"]})}),e.jsxs(oe,{children:[e.jsx(le,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-12 w-12 rounded-lg bg-brand/10 flex items-center justify-center shrink-0",children:e.jsx(Rs,{className:"h-6 w-6 text-brand"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-2xl",children:r.name}),r.trade_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.trade_name}),r.registration_status&&e.jsx(C,{variant:"outline",className:"mt-1",children:r.registration_status})]})]})}),e.jsxs(de,{className:"grid gap-2 text-sm md:grid-cols-2",children:[e.jsxs("div",{className:"md:col-span-2 flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Apelido:"}),j&&te?e.jsxs(e.Fragment,{children:[e.jsx(U,{value:V,onChange:s=>ae(s.target.value),className:"h-8 max-w-xs",maxLength:100,placeholder:"Ex.: primeiro nome"}),e.jsx(l,{size:"sm",onClick:()=>E.mutate(),disabled:E.isPending,children:"Salvar"}),e.jsx(l,{size:"sm",variant:"ghost",onClick:()=>{ae(r.nickname??""),$(!1)},children:"Cancelar"})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium",children:r.nickname||"—"}),j&&e.jsx(l,{size:"sm",variant:"ghost",className:"h-7 px-2",onClick:()=>$(!0),children:"Editar"})]})]}),r.cnpj&&e.jsxs("p",{children:["CNPJ: ",e.jsx("span",{className:"font-mono",children:r.cnpj})]}),r.opening_date&&e.jsxs("p",{children:["Abertura: ",r.opening_date]}),r.legal_nature&&e.jsxs("p",{children:["Natureza: ",r.legal_nature]}
5),r.company_size&&e.jsxs("p",{children:["Porte: ",r.company_size]}),r.main_cnae_code&&e.jsxs("p",{className:"md:col-span-2",children:["CNAE: ",r.main_cnae_code," ",r.main_cnae_desc?`— ${r.main_cnae_desc}`:""]}),r.contact_email&&e.jsxs("p",{className:"flex items-center gap-2",children:[e.jsx(ze,{className:"h-4 w-4 text-muted-foreground"})," ",r.contact_email]}),r.phone&&e.jsxs("p",{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"h-4 w-4 text-muted-foreground"})," ",r.phone]}),r.website&&e.jsxs("p",{className:"md:col-span-2",children:["Website: ",r.website]}),r.client_since&&e.jsxs("p",{children:["Cliente desde:"," ",e.jsx("span",{className:"font-medium",children:B(new Date(r.client_since+"T00:00:00"),"dd/MM/yyyy")})]}),(r.address_street||r.address_city)&&e.jsx("p",{className:"md:col-span-2 text-muted-foreground",children:[r.address_street,r.address_number,r.address_complement,r.address_district,r.address_city,r.address_state,r.address_zip].filter(Boolean).join(", ")}),Array.isArray(r.erps)&&r.erps.length>0&&e.jsxs("div",{className:"md:col-span-2 flex flex-wrap items-center gap-1 pt-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"ERPs:"}),[...r.erps].sort((s,a)=>s.localeCompare(a,"pt-BR")).map(s=>{const a=ye.isErpActive(s);return e.jsx(C,{variant:a?"secondary":"outline",className:"text-[10px] "+(a?"":"text-muted-foreground line-through"),title:a?void 0:"ERP inativo",children:s},s)})]})]})]}),j&&e.jsx(Xs,{companyId:i,initialClientSince:r.client_since??null,initialErps:r.erps??[],initialDefaultProjectId:r.default_project_id??null}),e.jsxs(oe,{children:[e.jsxs(le,{className:"flex flex-row items-center justify-between",children:[e.jsx(ce,{className:"text-base",children:"Contatos"}),j&&e.jsxs(l,{size:"sm",onClick:()=>{S({id:void 0,name:"",role:"",email:"",phone:"",is_primary:Ee.length===0}),q(!0)},children:[e.jsx(es,{className:"mr-1 h-4 w-4"})," Novo contato"]})]}),e.jsx(de,{children:v.isLoading?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando..."}):Ee.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum contato cadastrado."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Fe,{children:[e.jsx(Ae,{children:e.jsxs(ee,{children:[e.jsx(h,{children:"Nome"}),e.jsx(h,{children:"Cargo"}),e.jsx(h,{children:"E-mail"}),e.jsx(h,{children:"Telefone"}),e.jsx(h,{children:"Principal"}),j&&e.jsx(h,{className:"text-right",children:"Ações"})]})}),e.jsx(Me,{children:Ee.map(s=>e.jsxs(ee,{children:[e.jsx(x,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{className:"h-4 w-4 text-muted-foreground"}),s.name]})}),e.jsx(x,{className:"text-sm text-muted-foreground",children:s.role||"—"}),e.jsx(x,{className:"text-sm",children:s.email?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ze,{className:"h-3 w-3 text-muted-foreground"}),s.email]}):"—"}),e.jsx(x,{className:"text-sm",children:s.phone?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ze,{className:"h-3 w-3 text-muted-foreground"}),s.phone]}):"—"}),e.jsx(x,{children:s.is_primary?e.jsx(C,{variant:"default",className:"text-[10px]",children:"Principal"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),j&&e.jsx(x,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(l,{size:"sm",variant:"ghost",onClick:()=>{S({id:s.id,name:s.name??"",role:s.role??"",email:s.email??"",phone:s.phone??"",is_primary:!!s.is_primary}),q(!0)},children:"Editar"}),e.jsx(l,{size:"sm",variant:"ghost",onClick:()=>{confirm(`Remover contato "${s.name}"?`)&&cs.mutate(s.id)},children:e.jsx(Ns,{className:"h-3.5 w-3.5 text-destructive"})})]})})]},s.id))})]})})})]}),e.jsxs(oe,{children:[e.jsxs(le,{className:"flex flex-row items-center justify-between",children:[e.jsxs(ce,{className:"text-base flex items-center gap-2",children:[e.jsx(Bs,{className:"h-4 w-4"})," Contratos ativos"]}),j&&e.jsxs(l,{size:"sm",onClick:se,children:[e.jsx(es,{className:"mr-1 h-4 w-4"})," Novo contrato"]})]}),e.jsx(de,{children:k.isLoading?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando..."}):(k.data?.contracts??[]).length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum contrato ativo vinculado aos contatos de
5sta empresa."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Fe,{children:[e.jsx(Ae,{children:e.jsxs(ee,{children:[e.jsx(h,{children:"Contrato"}),e.jsx(h,{children:"Cliente"}),e.jsx(h,{children:"Projeto"}),e.jsx(h,{children:"Vigência"}),e.jsx(h,{children:"Valor"}),e.jsx(h,{children:"Status"}),e.jsx(h,{className:"text-right",children:"Ações"})]})}),e.jsx(Me,{children:(k.data?.contracts??[]).map(s=>{const a=M(s);return e.jsxs(ee,{className:"cursor-pointer hover:bg-muted/40",onClick:()=>Q(s.id),children:[e.jsx(x,{className:"font-medium",children:s.name}),e.jsx(x,{className:"text-sm",children:s.clientName}),e.jsx(x,{className:"text-sm text-muted-foreground",children:s.projectName}),e.jsxs(x,{className:"text-sm",children:[s.start_date?B(new Date(s.start_date+"T00:00:00"),"dd/MM/yyyy"):"—"," → ",s.end_date?B(new Date(s.end_date+"T00:00:00"),"dd/MM/yyyy"):"—"]}),e.jsx(x,{className:"text-sm tabular-nums",children:s.value!=null?Number(s.value).toLocaleString("pt-BR",{style:"currency",currency:s.currency||"BRL"}):"—"}),e.jsx(x,{children:e.jsx("span",{className:`inline-flex items-center rounded-md px-2 py-0.5 text-xs font-medium ${a.tone}`,children:a.label})}),e.jsx(x,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[(s.attachment_url||s.attachment_original_url)&&e.jsxs(l,{size:"sm",variant:"ghost",title:s.attachment_signed?"Baixar documento assinado":"Baixar documento",onClick:d=>{d.stopPropagation(),z(s)},children:[e.jsx(Qs,{className:"h-3.5 w-3.5 mr-1"}),"Baixar"]}),e.jsxs(l,{size:"sm",variant:"ghost",onClick:d=>{d.stopPropagation(),Q(s.id)},children:[e.jsx(Os,{className:"h-3.5 w-3.5 mr-1"}),"Ver detalhes"]})]})})]},s.id)})})]})})})]}),j&&e.jsxs(oe,{children:[e.jsxs(le,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ce,{className:"text-base flex items-center gap-2",children:[e.jsx(Vs,{className:"h-4 w-4"})," Usuários autorizados"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Pessoas deste cliente autorizadas a acessar o portal e abrir chamados."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{ref:X,type:"file",accept:".xlsx,.xls,.csv",className:"hidden",onChange:s=>{const a=s.target.files?.[0];a&&is(a)}}),e.jsx(l,{size:"sm",variant:"outline",onClick:ns,disabled:be,children:"Modelo .xlsx"}),e.jsxs(l,{size:"sm",variant:"outline",onClick:()=>X.current?.click(),disabled:be,children:[e.jsx(Hs,{className:"mr-1 h-4 w-4"})," ",be?"Importando...":"Importar planilha"]}),e.jsxs(l,{size:"sm",onClick:()=>K(!0),children:[e.jsx(Fs,{className:"mr-1 h-4 w-4"})," Convidar usuário"]})]})]}),e.jsx(de,{children:n.isLoading?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando..."}):(n.data??[]).length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:'Nenhum usuário autorizado. Use "Convidar usuário" para liberar o acesso.'}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Fe,{children:[e.jsx(Ae,{children:e.jsxs(ee,{children:[e.jsx(h,{children:"Nome"}),e.jsx(h,{children:"E-mail"}),e.jsx(h,{children:"Papel"}),e.jsx(h,{children:"Convite"}),e.jsx(h,{children:"Status"}),e.jsx(h,{className:"text-right",children:"Ações"})]})}),e.jsx(Me,{children:(n.data??[]).map(s=>e.jsxs(ee,{className:s.active?"":"opacity-60",children:[e.jsx(x,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{className:"h-4 w-4 text-muted-foreground"}),s.full_name||"—"]})}),e.jsx(x,{className:"text-sm",children:s.email||"—"}),e.jsx(x,{children:s.roles.length>0?s.roles.map(a=>e.jsx(C,{variant:"outline",className:"mr-1 text-[10px]",children:a==="requester"?"Solicitante":a},a)):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsx(x,{children:s.invite_status==="accepted"?e.jsx(C,{className:"text-[10px] bg-emerald-600 hover:bg-emerald-600 text-white",children:"Aceito"}):e.jsx(C,{variant:"outline",className:"text-[10px] border-amber-500 text-amber-600",children:"Pendente"})}),e.jsx(x,{children:s.active?e.jsx(C,{variant:"default",className:"text-[10px]",children:"Ativo"}):e.jsx(C,{variant:"secondary",className:"text-[10px]",children:"Inativo"})}),e.jsxs(x,{className:"text-right whitespace-nowrap",children:[e.jsxs(l,{size:"sm",variant:"ghost",title:"Entrar c
5omo este usuário no Portal",disabled:!s.active||Ce===s.email,onClick:()=>t(s.email,s.full_name),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"}),"Entrar como"]}),e.jsxs(l,{size:"sm",variant:"ghost",title:s.invite_status==="accepted"?"Enviar novo código de acesso por e-mail":"Reenviar convite",onClick:()=>Ie.mutate(s.id),disabled:Ie.isPending,children:[e.jsx(ze,{className:"h-3.5 w-3.5 mr-1"}),s.invite_status==="accepted"?"Novo acesso":"Reenviar"]}),e.jsx(l,{size:"sm",variant:"ghost",title:s.active?"Inativar":"Ativar",onClick:()=>ls.mutate({user_id:s.id,active:!s.active}),children:s.active?"Inativar":"Ativar"}),e.jsx(l,{size:"sm",variant:"ghost",title:"Excluir usuário",onClick:()=>{confirm(`Excluir "${s.full_name||s.email}" do sistema? Esta ação é permanente.`)&&os.mutate(s.id)},children:e.jsx(Gs,{className:"h-3.5 w-3.5 text-destructive"})})]})]},s.id))})]})})})]}),e.jsx(Je,{open:G,onOpenChange:K,children:e.jsxs(Ge,{children:[e.jsx(We,{children:e.jsx(Xe,{children:"Convidar usuário do cliente"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(b,{children:"Nome completo *"}),e.jsx(U,{value:w.full_name,onChange:s=>W({...w,full_name:s.target.value})})]}),e.jsxs("div",{children:[e.jsx(b,{children:"E-mail *"}),e.jsx(U,{type:"email",value:w.email,onChange:s=>W({...w,email:s.target.value})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["O usuário será cadastrado como ",e.jsx("strong",{children:"Solicitante"})," vinculado a este cliente e receberá um e-mail para definir a senha."]})]}),e.jsxs(Ye,{children:[e.jsx(l,{variant:"outline",onClick:()=>K(!1),children:"Cancelar"}),e.jsx(l,{onClick:()=>y.mutate(),disabled:!w.full_name.trim()||!w.email.trim()||y.isPending,children:"Enviar convite"})]})]})}),e.jsx(Je,{open:O,onOpenChange:q,children:e.jsxs(Ge,{children:[e.jsx(We,{children:e.jsx(Xe,{children:c.id?"Editar contato":"Novo contato"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(b,{children:"Nome *"}),e.jsx(U,{value:c.name,onChange:s=>S({...c,name:s.target.value})})]}),e.jsxs("div",{children:[e.jsx(b,{children:"Cargo"}),e.jsx(U,{value:c.role,onChange:s=>S({...c,role:s.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(b,{children:"E-mail"}),e.jsx(U,{type:"email",value:c.email,onChange:s=>S({...c,email:s.target.value})})]}),e.jsxs("div",{children:[e.jsx(b,{children:"Telefone"}),e.jsx(U,{value:c.phone,onChange:s=>S({...c,phone:s.target.value})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{checked:c.is_primary,onCheckedChange:s=>S({...c,is_primary:s===!0})}),e.jsx(b,{className:"!mt-0",children:"Contato principal"})]})]}),e.jsxs(Ye,{children:[e.jsx(l,{variant:"outline",onClick:()=>q(!1),children:"Cancelar"}),e.jsx(l,{onClick:()=>Le.mutate(),disabled:!c.name.trim()||Le.isPending,children:"Salvar"})]})]})}),e.jsx(Ds,{open:!!I,onOpenChange:s=>!s&&he(null),creds:I})]})}export{Da as component};

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.