1import{j as e}from"./ui-vendor-DugvyhkM.js";import{r as i,i as je,e as ge}from"./react-vendor-CnbS1iJ1.js";import{g as we}from"./adminUtils-BodFSms_.js";import{s as x,f as c,k as Ne,L as F,B as o,X as _e}from"./index-Bg0TxxV_.js";import{C,b as k,c as P,a as E}from"./card-Cae1mpFA.js";import{B as re}from"./badge-CzHqQw3k.js";import{S as ve}from"./separator-BR_2C1oT.js";import{I as ye}from"./input-7TDv-tmI.js";import{L as be}from"./label-kuCvhSP_.js";import{T as Se,a as Ce,b as W,e as L,c as ke,d as T}from"./table-BSabRjfe.js";import{D as G,b as K,c as $,d as X,e as J,f as Q}from"./dialog-Dubnefxk.js";import{S as te,a as ne,b as ie,c as le,d as D}from"./select-CBOQZhf-.js";import{l as U}from"./activityLogger-Bs2uaUcR.js";import{P as Pe}from"./usePlanFeatures-BlYPiVAV.js";import{A as Ee}from"./arrow-left-Da74-hSe.js";import{U as Te}from"./user-check-gSN7FJEV.js";import{S as oe}from"./square-pen-9-5gQlB8.js";import{C as De}from"./credit-card-C7wqqMsd.js";import{U as Y}from"./users-NgL9bi2j.js";import{B as Ie}from"./building-2-DwC9Ar9P.js";import{S as ce}from"./smartphone-C3IDloT3.js";import{M as Re}from"./message-circle-DwSDMpzy.js";import{U as de}from"./user-plus-D8iXWKsB.js";import{C as me}from"./check-CLse9FI2.js";import{K as ue}from"./key-round-_mKICpRz.js";import{E as Ae}from"./eye-off-Bb3IF1jD.js";import{E as Le}from"./eye-BQxYDZe1.js";import{C as Ue}from"./copy-CfZj5p-r.js";import"./supabase-vendor-DOL-USaH.js";import"./circle-x-BEDxBoPB.js";import"./wifi-off-BwEhnRk0.js";import"./ban-Cp7FqmPH.js";import"./clock-CpxfZcn9.js";import"./handshake-Cs7wOfcO.js";import"./wifi-8diP91nL.js";import"./circle-check-big-Cq3GO93E.js";import"./charts-vendor-BthknRg3.js";import"./query-vendor-VfPrV_BW.js";import"./chevron-down-B8zXvv0T.js";function Me(N){const[t,q]=i.useState(null),[a,M]=i.useState([]),[j,I]=i.useState([]),[z,H]=i.useState(!0),[y,g]=i.useState(!1);i.useEffect(()=>{N&&_()},[N]);async function _(){try{const{data:l,error:r}=await x.from("workspaces").select("*").eq("id",N).single();if(r)throw r;q(l);const{data:u}=await x.rpc("get_workspace_members",{p_workspace_id:N});if(u&&u.length>0){const w=u.map(d=>({id:d.user_id,user_id:d.user_id,role:d.role,is_active:d.is_active??!0,profile:{full_name:d.full_name,email:d.email}}));M(w)}else{const{data:w}=await x.from("user_roles").select("id, user_id, role").eq("workspace_id",N),d=(w||[]).map(h=>h.user_id);let R={};if(d.length>0){const{data:h}=await x.from("profiles").select("user_id, full_name, avatar_url").in("user_id",d);(h||[]).forEach(A=>{R[A.user_id]=A})}const B=(w||[]).map(h=>({...h,profile:R[h.user_id]||null}));M(B)}const{data:p}=await x.from("plans").select("id, name, slug, base_price, max_instances, max_groups, max_messages_per_month, max_contacts").eq("is_active",!0);I(p||[])}catch(l){console.error("Error fetching tenant details:",l),c.error("Erro ao carregar detalhes do workspace")}finally{H(!1)}}async function V(l){if(t)try{g(!0);const r=l==="suspended"||l==="cancelled",{error:u}=await x.from("workspaces").update({status:l,is_suspended:r,suspended_at:r?new Date().toISOString():null}).eq("id",t.id);if(u)throw u;c.success("Situação alterada com sucesso"),U({action:"update",entityType:"workspace",entityId:t.id,entityName:t.name,source:"admin",details:{operation:"change_status",old_status:t.status,new_status:l}}),_()}catch(r){console.error("Error changing status:",r),c.error("Erro ao alterar situação")}finally{g(!1)}}async function b(l){if(!(!t||!l))try{g(!0);const r=j.find(p=>p.id===l);if(!r)throw new Error("Plano não encontrado");const{error:u}=await x.from("workspaces").update({plan_id:l,plan:r.slug||null,max_instances:r.max_instances??t.max_instances,max_groups:r.max_groups??t.max_groups,max_messages_per_month:r.max_messages_per_month??t.max_messages_per_month}).eq("id",t.id);if(u)throw u;c.success("Plano alterado e limites sincronizados com sucesso"),U({action:"update",entityType:"workspace",entityId:t.id,entityName:t.name,source:"admin",details:{operation:"change_plan",old_plan:t.plan,new_plan:r.slug,new_plan_name:r.name}}),_()}catch(r){console.error("Error changing plan:",r),c.error("Erro ao alterar plano")}finally{g(!1)}}const O=j.find(l=>l.id===t?.plan_id);return{workspace:t,teamMembers:a,plans:j,isLoading:z,isSaving:y,currentPlan:O,handleChangeStatus:V,handleChangePlan:b,fetchTenantDetails:_}}function ys(){const{id:N}=je(),t=ge(),{startImpersonation:q}=Ne(),a=Me(N),[M,j]=i.useState(!1),[I,z]=i.useState(""),[H,y]=i.useState(!1),[g,_]=i.useState(""),[V,b]=i.useState(!1),[O,l]=i.useState(""),[r,u]=i.useState(""),[p,w]=i.useState(""),[d,R]=i.useState(!1),[B,h]=i.useState(!1),[A,Z]=i.useState([]);i.useEffect(()=>{async function s(){const n=a.workspace?.plan_id;if(!n){Z([]);return}const{data:f}=await x.from("plan_features").select("*").eq("plan_id",n).eq("is_enabled",!0);Z(f||[])}s()},[a.workspace?.plan_id]);const pe=()=>{if(!a.workspace)return;const s=a.workspace;U({action:"impersonate",entityType:"workspace",entityId:s.id,entityName:s.name,source:"admin",details:{operation:"impersonation"}}),q({id:s.id,name:s.name,slug:s.slug,short_id:s.short_id||s.slug,owner_id:s.owner_id,plan:s.plan||"free",max_instances:s.max_instances,max_groups:s.max_groups,max_messages_per_month:s.max_messages_per_month,is_suspended:s.is_suspended,suspended_reason:s.suspended_reason||null,subscription_expires_at:s.subscription_expires_at||null}),t("/workspace")};function ee(){const s="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";let n="";for(let f=0;f<10;f++)n+=s.charAt(Math.floor(Math.random()*s.length));return n}const xe=(s,n)=>{l(s),u(n),w(ee()),R(!0),b(!0)},he=async()=>
1{if(!p||p.length<6){c.error("A senha deve ter pelo menos 6 caracteres");return}h(!0);try{const{data:s,error:n}=await x.functions.invoke("reset-tenant-password",{body:{user_id:O,new_password:p}});if(n||s?.error){c.error(s?.error||n?.message||"Erro ao redefinir senha");return}c.success("Senha redefinida com sucesso!",{description:`Nova senha: ${p}`,duration:15e3}),U({action:"update",entityType:"user",entityId:O,entityName:r,workspaceId:a.workspace?.id,source:"admin",details:{operation:"password_reset"}}),b(!1)}catch(s){console.error(s),c.error("Erro ao redefinir senha")}finally{h(!1)}};if(a.isLoading)return e.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:e.jsx(F,{className:"h-8 w-8 animate-spin text-primary"})});if(!a.workspace)return e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Workspace não encontrado"}),e.jsx(o,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/tenants"),children:"Voltar"})]});const m=a.workspace,se=new Set(A.map(s=>s.feature_key)),fe=Pe.filter(s=>s.type==="features"&&s.features?.length);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(o,{variant:"ghost",size:"icon",onClick:()=>t("/admin/tenants"),children:e.jsx(Ee,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:m.name}),we(m.status||"active")]}),e.jsxs("p",{className:"text-muted-foreground",children:["Slug: ",m.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(o,{onClick:pe,children:[e.jsx(Te,{className:"h-4 w-4 mr-2"}),"Entrar como Suporte"]}),e.jsxs(o,{variant:"outline",onClick:()=>j(!0),children:[e.jsx(oe,{className:"h-4 w-4 mr-2"}),"Alterar Plano"]}),e.jsxs(o,{variant:"outline",onClick:()=>{_(m.status||"active"),y(!0)},children:[e.jsx(oe,{className:"h-4 w-4 mr-2"}),"Situação"]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs(C,{children:[e.jsxs(k,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsx(P,{className:"text-sm font-medium",children:"Plano"}),e.jsx(De,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(E,{children:[e.jsx("div",{className:"text-2xl font-bold",children:a.currentPlan?.name||m.plan||"N/A"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["R$ ",(a.currentPlan?.base_price||0).toLocaleString("pt-BR",{minimumFractionDigits:2}),"/mês"]})]})]}),e.jsxs(C,{children:[e.jsxs(k,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsx(P,{className:"text-sm font-medium",children:"Membros"}),e.jsx(Y,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(E,{children:[e.jsx("div",{className:"text-2xl font-bold",children:a.teamMembers.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"usuários na equipe"})]})]}),e.jsxs(C,{children:[e.jsxs(k,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsx(P,{className:"text-sm font-medium",children:"Criado em"}),e.jsx(Ie,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(E,{children:[e.jsx("div",{className:"text-2xl font-bold",children:new Date(m.created_at).toLocaleDateString("pt-BR")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"data de criação"})]})]})]}),e.jsxs(C,{children:[e.jsx(k,{children:e.jsxs(P,{className:"flex items-center gap-2",children:[e.jsx(ce,{className:"h-5 w-5"}),"Limites do Plano"]})}),e.jsx(E,{children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{className:"h-5 w-5 text-primary"}),e.jsx("span",{children:"Instâncias"})]}),e.jsx("span",{className:"font-bold",children:m.max_instances})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{className:"h-5 w-5 text-primary"}),e.jsx("span",{children:"Grupos"})]}),e.jsx("span",{className:"font-bold",children:m.max_groups})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"h-5 w-5 text-primary"}),e.jsx("span",{children:"Msgs/mês"})]}),e.jsx("span",{className:"font-bold",children:m.max_messages_per_month?.toLocaleStr
1ing()})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(de,{className:"h-5 w-5 text-primary"}),e.jsx("span",{children:"Contatos"})]}),e.jsx("span",{className:"font-bold",children:m.max_contacts?.toLocaleString()||"â"})]})]})})]}),A.length>0&&e.jsxs(C,{children:[e.jsx(k,{children:e.jsxs(P,{className:"flex items-center gap-2",children:[e.jsx(me,{className:"h-5 w-5"}),"Recursos do Plano"]})}),e.jsx(E,{className:"space-y-4",children:fe.map(s=>{const n=s.features;return n.some(v=>se.has(v.key))?e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-2",children:s.label}),e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:n.map(v=>{const S=se.has(v.key);return e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[S?e.jsx("div",{className:"h-5 w-5 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(me,{className:"h-3 w-3 text-primary"})}):e.jsx("div",{className:"h-5 w-5 rounded-full bg-muted flex items-center justify-center",children:e.jsx(_e,{className:"h-3 w-3 text-muted-foreground/40"})}),e.jsx("span",{className:S?"text-foreground":"text-muted-foreground/50",children:v.label})]},v.key)})}),e.jsx(ve,{className:"mt-3"})]},s.key):null})})]}),e.jsxs(C,{children:[e.jsx(k,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(P,{className:"flex items-center gap-2",children:[e.jsx(Y,{className:"h-5 w-5"}),"Equipe"]}),e.jsxs(o,{size:"sm",className:"gap-2",onClick:()=>{(async()=>{const n=prompt("Email do novo usuário:");if(!n)return;const f=prompt("Senha (mÃn. 6 caracteres):");if(!f||f.length<6){c.error("Senha deve ter no mÃnimo 6 caracteres");return}const v=prompt("Nome completo:")||"";try{const{data:S,error:ae}=await x.functions.invoke("create-workspace-user",{body:{workspace_id:m.id,email:n,password:f,full_name:v,role:"operator"}});if(ae||S?.error){c.error(S?.error||ae?.message||"Erro ao criar usuário");return}c.success(`Usuário ${n} criado com sucesso`),U({action:"create",entityType:"user",entityName:n,workspaceId:m.id,source:"admin",details:{operation:"create_user"}}),a.fetchTenantDetails()}catch{c.error("Erro ao criar usuário")}})()},children:[e.jsx(de,{className:"h-4 w-4"}),"Criar Usuário"]})]})}),e.jsx(E,{children:e.jsxs(Se,{children:[e.jsx(Ce,{children:e.jsxs(W,{children:[e.jsx(L,{children:"Nome"}),e.jsx(L,{children:"Email"}),e.jsx(L,{children:"Função"}),e.jsx(L,{children:"Status"}),e.jsx(L,{className:"text-right",children:"Ações"})]})}),e.jsxs(ke,{children:[a.teamMembers.map(s=>e.jsxs(W,{className:s.is_active===!1?"opacity-60":"",children:[e.jsx(T,{children:e.jsx("p",{className:"font-medium",children:s.profile?.full_name||"Sem nome"})}),e.jsx(T,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:s.profile?.email||"â"})}),e.jsx(T,{children:e.jsx(re,{variant:"outline",children:s.role})}),e.jsx(T,{children:e.jsx(re,{variant:s.is_active!==!1?"default":"destructive",className:"text-[10px]",children:s.is_active!==!1?"Ativo":"Desativado"})}),e.jsx(T,{className:"text-right",children:e.jsxs(o,{variant:"outline",size:"sm",onClick:()=>xe(s.user_id,s.profile?.full_name||s.profile?.email||"Usuário"),children:[e.jsx(ue,{className:"h-3.5 w-3.5 mr-1.5"}),"Redefinir Senha"]})})]},s.id)),a.teamMembers.length===0&&e.jsx(W,{children:e.jsx(T,{colSpan:5,className:"text-center text-muted-foreground",children:"Nenhum membro"})})]})]})})]}),e.jsx(G,{open:M,onOpenChange:j,children:e.jsxs(K,{children:[e.jsxs($,{children:[e.jsx(X,{children:"Alterar Plano"}),e.jsx(J,{children:"Os limites do workspace serão sincronizados automaticamente com o plano selecionado."})]}),e.jsx("div",{className:"py-4",children:e.jsxs(te,{value:I,onValueChange:z,children:[e.jsx(ne,{children:e.jsx(ie,{placeholder:"Selecione um plano"})}),e.jsx(le,{className:"bg-popover border-border",children:a.plans.map(s=>e.jsxs(D,{value:s.id,children:[s.name," - R$ ",s.base_price.toLocaleString("pt-BR",{minimumFractionDigits:2})]},s.id))})]})}),e.jsxs(Q,{children:[e.jsx(o,{variant:"outline",onClick:()=>j(!1),children:"Cancelar"}),e.jsxs(o,{onClick:()=>{a.handleChangePlan(I),j(!1)},disabled:!I||a.isSaving,children:[a.isSaving?e.jsx(F,{className:"h-4 w-4 animate-spin mr-2"}):null,"Salvar"]})]})]})}),e.jsx(G,{open:H,onOpenChange:y,children:e.jsxs(K,{children:[e.jsxs($,{children:[e.jsx(X,{children:"Alterar Situação"}),e.jsx(J,{children:"Selecione a nova situação do workspace"})]}),e.jsx("div",{className:"py-4",children:e.jsxs(te,{value:g,onValueChange:_,children:[e.jsx(ne,{children:e.jsx(ie,{placeholder:"Selecione a situação"})}),e.jsxs(le,{className:"bg-popover border-border",children:[e.jsx(D,{value:"trial",children:"Trial"}),e.jsx(D,{value:"active",children:"Ativa"}),e.jsx(D,{value:"suspended",children:"Suspensa"}),e.jsx(D,{value:"cancelled",children:"Cancelada"}),e.jsx(D,{value:"barter",children:"Permuta"})]})]})}),e.jsxs(Q,{children:[e.jsx(o,{variant:"outline",onClick:()=>y(!1),children:"Cancelar"}),e.jsxs(o,{onClick:()=>{a.handleChangeStatus(g),y(!1)},disabled:!g||a.isSaving,children:[a.isSaving?e.jsx(F,{className:"h-4 w-4 animate-spin mr-2"}):null,"Salvar"]})]})]})}),e.jsx(G,{open:V,onOpenChange:b,children:e.jsxs(K,{children:[e.jsxs($,{children:[e.jsxs(X,{className:"flex items-center gap-2",children:[e.jsx(ue,{className:"h-5 w-5"}),"Redefinir Senha"]}),e.jsxs(J,{children:["Defina uma nova senha para ",e.jsx("strong",{children:r})]})]}),e.jsxs("div",{className:"py-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(be,{children:"Nova Senha"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{type:d?"text":"password",value:p,onChange:s=>w(s.target.value),placeholder:"MÃnimo 6 caracteres"}),e.jsx(o,{type:"button",variant:"ghost",size:"icon",className:"absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8",onClick:()=>R(!d),children:d?e.jsx(Ae,{className:"h-4 w-4"}):e.jsx(Le,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(o,{type:"button",variant:"outline",size:"sm",onClick:()=>w(ee()),children:"Gerar nova senha"}),e.jsxs(o,{type:"button",variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(p),c.success("Senha copiada!")},children:[e.jsx(Ue,{className:"h-3.5 w-3.5 mr-1.5"}),"Copiar"]})]})]}),e.jsxs(Q,{children:[e.jsx(o,{variant:"outline",onClick:()=>b(!1),children:"Cancelar"}),e.jsxs(o,{onClick:he,disabled:B||p.length<6,children:[B?e.jsx(F,{className:"h-4 w-4 animate-spin mr-2"}):null,"Redefinir Senha"]})]})]})})]})}export{ys 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.