1import{r as o,j as e}from"./vendor-query-CeYLmLzt.js";import{ag as we,au as Ce,a as h,s as u,ai as de,aj as H,d8 as ke,E as Ae,K as ue,a0 as Te,a1 as Ee,_ as O,$ as me,a9 as he,F as Pe,cD as Ie}from"./index-C9GI-6TB.js";import{L as x}from"./label-CF4wLb5c.js";import{s as Fe,e as Le,D as xe}from"./date-picker-input-Cbp7v9ZI.js";import{S as Ve}from"./scrollable-table-CnSgk_wl.js";import{S as P,a as I,b as F,c as L,d as n}from"./select-CIRUJm7L.js";import{S as ze}from"./searchable-select-qwxda2Fa.js";import{A as Ue,h as Be,a as Me,b as qe,c as He,d as Oe,e as $e,g as Re,f as Xe}from"./alert-dialog-BRbFycEL.js";import{u as Ke}from"./useSorting-DmGCKVFJ.js";import{u as We}from"./TablePagination-Dqymv64Q.js";import{e as Ze}from"./exportUtils-WyQpTRFb.js";import{a as y}from"./table-CLkXubLJ.js";import{d as V,c as Ge}from"./compact-table-NO3Dd7k9.js";import{k as pe}from"./format-BwfTtEE5.js";import"./vendor-react-BPOX-wWs.js";import"./vendor-supabase-Cc8l7PMd.js";import"./vendor-motion-BtWo1fWB.js";import"./differenceInCalendarDays-Bu8By2ZG.js";import"./addDays-DSCzji-7.js";import"./pt-BR-Bksn6Y5X.js";import"./useScrollShadow-C0qIt916.js";import"./empty-state-DpNMpomS.js";import"./index-BdQq_4o_.js";import"./index-B1iJygXQ.js";import"./xlsx-DREyypUJ.js";import"./dateUtils-fh0gTqyg.js";const _a=()=>{we();const p=Ce(),[w,z]=o.useState([]),[$,R]=o.useState([]),[fe,X]=o.useState([]),[ge,K]=o.useState([]),[je,C]=o.useState(!0),[W,Z]=o.use
1State(!1),[ve,be]=o.useState(!1),[c,j]=o.useState("all"),[v,G]=o.useState(()=>pe(Fe(new Date),"yyyy-MM-dd")),[b,J]=o.useState(()=>pe(Le(new Date),"yyyy-MM-dd")),[N,Q]=o.useState("all"),[D,Y]=o.useState("all"),[_,ee]=o.useState("all"),[S,ae]=o.useState("all");o.useEffect(()=>{(async()=>{const{data:{user:s}}=await u.auth.getUser();if(s){const{data:l}=await u.rpc("is_admin_by_profile",{user_uuid:s.id});be(l===!0)}})()},[]),o.useEffect(()=>{p&&se()},[p]);const se=async()=>{if(!p)return;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(p)){R([]),K([]),X([]),z([]),C(!1),h.error("Empresa selecionada é inválida. Selecione novamente.");return}C(!0);try{const{data:s,error:l}=await u.from("documentos_arquivos").select("id, nome, file_name, pasta_id, subpasta").eq("empresa_id",p).order("nome",{ascending:!0});if(l)throw l;if(R(s||[]),!s||s.length===0){z([]),C(!1);return}const d=[...new Set(s.map(t=>t.pasta_id).filter(Boolean))];let f=[];if(d.length>0){const{data:t}=await u.from("documentos_pastas").select("id, nome").in("id",d).order("nome",{ascending:!0});f=t||[]}K(f);const B=s.map(t=>t.id).filter(Boolean);let T=[];const le=100;if(B.length>0)for(let t=0;t<B.length;t+=le){const g=B.slice(t,t+le),{count:q}=await u.from("documentos_arquivos_acesso").select("*",{count:"exact",head:!0}).in("documento_id",g),m=q||0,ie=1e3;for(let E=0;E<m;E+=ie){const{data:ne,error:ce}=await u.from("documentos_arquivos_acesso").select(` 2 id, 3 documento_id, 4 usuario_id, 5 user_id, 6 tipo_operacao, 7 created_at 8 `).in("documento_id",g).order("created_at",{ascending:!1}).range(E,E+ie-1);if(ce)throw ce;ne?.length&&(T=T.concat(ne))}}const re=[...new Set((T||[]).map(t=>t.usuario_id).filter(Boolean))];let M=[];if(re.length>0){const{data:t}=await u.from("usuarios").select("id, full_name, email").in("id",re).order("full_name",{ascending:!0});M=t||[]}X(M);const ye=(T||[]).map(t=>{const g=s.find(m=>m.id===t.documento_id),q=f?.find(m=>m.id===g?.pasta_id);return{...t,usuario:M?.find(m=>m.id===t.usuario_id),documento:g?{...g,pasta_nome:q?.nome}:void 0}});z(ye)}catch(s){console.error("LogsDocumentos fetchData error:",s);const l=[s?.message,s?.details,s?.hint].filter(Boolean).join(" - ");h.error("Erro ao carregar dados: "+(l||"Falha inesperada"))}finally{C(!1)}},r=o.useMemo(()=>w.filter(a=>!(c!=="all"&&a.tipo_operacao!==c||N!=="all"&&a.documento_id!==N||D!=="all"&&a.usuario_id!==D||_!=="all"&&a.documento?.pasta_id!==_||S!=="all"&&a.documento?.subpasta!==S||v&&a.created_at.substring(0,10)<v||b&&a.created_at.substring(0,10)>b)),[w,c,N,D,_,S,v,b]),{sortedItems:Ne,requestSort:k,getSortDirection:A}=Ke(r),i=We(Ne,{itemsPerPage:50}),U=o.useMemo(()=>{const a=r.length,s=r.filter(d=>d.tipo_operacao==="Visualização").length,l=r.filter(d=>d.tipo_operacao==="Download").length;return{total:a,visualizacoes:s,downloads:l}},[r]),te=a=>{const s=new Date(a);return isNaN(s.getTime())?a:s.toLocaleString("pt-BR",{timeZone:"America/Sao_Paulo",day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}).replace(","," -")},De=()=>{j("all"),Q("all"),Y("all"),ee("all"),ae("all"),G(void 0),J(void 0)},oe=c!=="all"||N!=="all"||D!=="all"||_!=="all"||S!=="all"||v||b,_e=async()=>{if(r.length===0){h.error("Não há logs para excluir");return}Z(!0);try{const a=r.map(l=>l.id),s=100;for(let l=0;l<a.length;l+=s){const d=a.slice(l,l+s),{error:f}=await u.from("documentos_arquivos_acesso").delete().in("id",d);if(f)throw f}h.success(`${a.length} log(s) excluÃdo(s) com sucesso`),await se()}catch(a){console.error("Erro ao excluir logs:",a),h.error("Erro ao excluir logs: "+(a.message||"Falha inesperada"))}finally{Z(!1)}},Se=()=>{if(r.length===0){h.error("Não há dados para exportar");return}Ze(r,[{key:"documento.nome",label:"Documento"},{key:"documento.file_name",label:"Arquivo"},{key:"documento.pasta_nome",label:"Pasta"},{key:"documento.subpasta",label:"Subpasta"},{key:"usuario.full_name",label:"Usuário"},{key:"usuario.email",label:"E-mail"},{key:"tipo_operacao",label:"Operação"},{key:"created_at",label:"Data/Hora",format:s=>te(s)}],`Logs-Acessos-${new Date().toISOString().split("T")[0]}`),h.success("Exportação realizada com sucesso")};return p?e.jsx(de,{title:"Acessos",children:e.jsxs("div",{className:"flex flex-col h-[calc(100vh-5rem)] md:h-[calc(100vh-4rem)] overflow-hidden pt-1",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-4 pb-4 px-0.5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(H,{title:"Total de Acessos",value:U.total,icon:ke,iconColor:"text-blue-500",iconBgColor:"bg-blue-500/10",valueColor:"text-blue-600",selected:c==="all",selectionColor:"ring-blue-500",borderColor:"border-blue-500/50",variant:"compact",onClick:()=>j("all")}),e.jsx(H,{title:"Visualizações",value:U.visualizacoes,icon:Ae,iconColor:"text-blue-500",iconBgColor:"bg-blue-500/10",valueColor:"text-blue-600",selected:c==="Visualização",selectionColor:"ring-blue-500",borderColor:"border-blue-500/50",variant:"compact",onClick:()=>j("Visualização")}),e.jsx(H,{title:"Downloads",value:U.downloads,icon:ue,iconColor:"text-green-500",iconBgColor:"bg-green-500/10",valueColor:"text-green-600",selected:c==="Download",selectionColor:"ring-green-500",borderColor:"border-green-500/50",variant:"compact",onClick:()=>j("Download")})]}),e.jsx(Te,{children:e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(x,{children:"Tipo"}),e.jsxs(P,{value:c,onValueChange:a=>j(a),children:[e.jsx(I,{className:"w-full",children:e.jsx(F,{})}),e.jsxs(L,{children:[e.jsx(n,{value:"all",children:"Todos"}),e.jsx(n,{value:"Visualização",children:"Visualização"}),e.jsx(n,{value:"Download",children:"Download"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(x,{children:"Pasta"}),e.jsxs(P,{value:_,onValueChange:ee,children:[e.jsx(I,{className:"w-full",children:e.jsx(F,{placeholder:"Pasta"})}),e.jsxs(L,{children:[e.jsx(n,{value:"all",children:"Todas"}),ge.map(a=>e.jsx(n,{value:a.id,children:a.nome},a.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(x,{children:"Subpasta"}),e.jsxs(P,{value:S,onValueChange:ae,children:[e.jsx(I,{className:"w-full",children:e.jsx(F,{placeholder:"Todas"})}),e.jsxs(L,{children:[e.jsx(n,{value:"all",children:"Todas"}),[...new Set($.map(a=>
8a.subpasta).filter(Boolean))].sort().map(a=>e.jsx(n,{value:a,children:a},a))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(x,{children:"Documento"}),e.jsx(ze,{options:[{value:"all",label:"Todos"},...$.map(a=>({value:a.id,label:a.nome}))||[]],value:N,onValueChange:Q,placeholder:"Documento",className:"w-full",hideSearchIcon:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(x,{children:"Usuário"}),e.jsxs(P,{value:D,onValueChange:Y,children:[e.jsx(I,{className:"w-full",children:e.jsx(F,{placeholder:"Usuário"})}),e.jsxs(L,{children:[e.jsx(n,{value:"all",children:"Todos"}),fe.map(a=>e.jsx(n,{value:a.id,children:a.full_name||a.email},a.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(x,{children:"De"}),e.jsx(xe,{value:v,onChange:G,placeholder:"Data Inicial"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(x,{children:"Até"}),e.jsx(xe,{value:b,onChange:J,placeholder:"Data Final"})]}),e.jsxs("div",{className:"col-span-2 md:col-span-2 flex gap-2 justify-end flex-wrap",children:[oe&&e.jsxs(O,{variant:"destructive",onClick:De,children:[e.jsx(me,{className:"h-4 w-4 mr-1"}),"Limpar"]}),e.jsxs(O,{className:"bg-blue-600 hover:bg-blue-700",onClick:Se,disabled:r.length===0,children:[e.jsx(ue,{className:"h-4 w-4 mr-2"}),"Exportar"]}),ve&&e.jsxs(Ue,{children:[e.jsx(Be,{asChild:!0,children:e.jsxs(O,{variant:"destructive",disabled:r.length===0||W,children:[e.jsx(he,{className:"h-4 w-4 mr-2"}),W?"Excluindo...":"Excluir Logs"]})}),e.jsxs(Me,{children:[e.jsxs(qe,{children:[e.jsx(He,{children:"Excluir Logs de Acesso"}),e.jsxs(Oe,{children:["Você está prestes a excluir ",e.jsx("strong",{children:r.length})," registro(s) de log.",oe&&e.jsx("span",{className:"block mt-2 text-amber-600",children:"â ï¸ Os filtros estão ativos. Apenas os logs filtrados serão excluÃdos."}),e.jsx("span",{className:"block mt-2",children:"Esta ação não pode ser desfeita."})]})]}),e.jsxs($e,{children:[e.jsxs(Re,{className:"flex items-center gap-2",children:[e.jsx(me,{className:"h-4 w-4"}),"Fechar"]}),e.jsxs(Xe,{onClick:_e,className:"bg-black text-white hover:bg-black/90 flex items-center gap-2",children:[e.jsx(he,{className:"h-4 w-4"}),"Excluir"]})]})]})]})]})]})]})})]}),e.jsx(Ve,{data:r,paginatedItems:i.paginatedItems,isLoading:je,emptyMessage:"Nenhum registro de acesso encontrado",emptySearchMessage:"Nenhum registro encontrado com os filtros aplicados",hasSearch:w.length>0&&r.length===0,getRowKey:a=>a.id,pagination:{currentPage:i.currentPage,totalPages:i.totalPages,totalItems:i.totalItems,startIndex:i.startIndex,endIndex:i.endIndex,hasNextPage:i.hasNextPage,hasPrevPage:i.hasPrevPage,goToPage:i.goToPage,totalUnfilteredItems:w.length},renderHeader:()=>e.jsxs(e.Fragment,{children:[e.jsx(V,{sortDirection:A("documento_id"),onSort:()=>k("documento_id"),className:"normal-case",children:"Documento"}),e.jsx(Ge,{className:"normal-case",children:"Pasta e Subpasta"}),e.jsx(V,{sortDirection:A("usuario_id"),onSort:()=>k("usuario_id"),className:"normal-case",children:"Usuário"}),e.jsx(V,{sortDirection:A("tipo_operacao"),onSort:()=>k("tipo_operacao"),className:"w-[120px] normal-case",children:"Operação"}),e.jsx(V,{sortDirection:A("created_at"),onSort:()=>k("created_at"),className:"w-[180px] normal-case",children:"Data e Hora"})]}),renderRow:a=>e.jsxs(e.Fragment,{children:[e.jsx(y,{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:a.documento?.nome||"Documento"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a.documento?.file_name})]})]})}),e.jsx(y,{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ie,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:a.documento?.pasta_nome||"-"}),a.documento?.subpasta&&e.jsx("span",{className:"text-xs text-muted-foreground",children:a.documento.subpasta})]})]})}),e.jsx(y,{className:"py-1.5",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:a.usuario?.full_name||"Usuário"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a.usuario?.email})]})}),e.jsx(y,{className:"py-1.5",children:e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${a.tipo_operacao==="Visualização"?"bg-blue-600 text-white":"bg-black text-white"}`,children:a.tipo_operacao})}),e.jsx(y,{className:"text-sm text-muted-foreground py-1.5",children:te(a.created_at)})]})})]})}):e.jsx(de,{children:e.jsx("div",{className:"space-y-6",children:e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Selecione uma empresa para visualizar os logs de acesso."})})})};export{_a 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.