1import{r as N,j as e}from"./index-C86y2ZZw.js";import{ao as M,bL as Ee,bM as Re,i as y,t as Ae,bN as Me,y as ue,I as B,B as V,b8 as Ie,d6 as pe,f as A,h as he,a8 as Le,bo as Q,bp as K,bq as Y,br as X,bs as L,ah as De,a9 as Pe,dc as le,z as ge,aC as Fe,aD as Oe,V as fe,cC as je,az as qe,n as ze,ag as He,j as $e,D as J,a as ee,b as se,c as ae,aF as te,bH as ne,v as ve,w as D,bj as Be,W as Ne,u as ce,bG as Ve,cN as Ue,R as Qe}from"./App-BsV2Qj_s.js";import{A as Ke,a as Ye,b as Xe}from"./alert-MODGBXRs.js";import{u as W,w as Ge}from"./xlsx-uoQkVabA.js";import{C as We}from"./checkbox-DGvc0ATb.js";import{F as Ze}from"./filter-C7dW9fEP.js";import{Q as _e}from"./qr-code-CuDlW3Q3.js";import{T as be,a as ye,b as z,c as T,d as we,e as S}from"./table-CY4dzb33.js";import{S as Ce}from"./scan-line-hUaaPvIw.js";import{C as Je}from"./circle-x-CycC-034.js";import{R as es}from"./repeat-DByX8b90.js";import{T as ss,a as as,b as re}from"./tabs-CCb_Hfd7.js";import{T as Se}from"./textarea-CGKHQQc9.js";import{s as I}from"./client-DMrl-iUj.js";import{S as oe}from"./shield-off-BZ_91Axv.js";import{N as ts}from"./nfc-AU97-M7n.js";import{R as ns}from"./radio-CRK81yxQ.js";import{p as cs}from"./ticketSeatParsing-D_Xg3vr-.js";function de({label:s,placeholder:t,options:l,selected:c,onChange:r,width:h="w-[420px]"}){var g;const[d,x]=N.useState(!1),[p,o]=N.useState(""),a=N.useMemo(()=>{const m=p.trim().toLowerCase();return m?l.filter(b=>b.label.toLowerCase().includes(m)||(b.hint??"").toLowerCase().includes(m)):l},[l,p]),u=m=>{r(c.includes(m)?c.filter(b=>b!==m):[...c,m])},f=c.length===0?t:c.length===1?((g=l.find(m=>m.value===c[0]))==null?void 0:g.label)??"1 seleccionado":`${c.length} seleccionados`;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(M,{className:"text-xs text-muted-foreground",children:s}),e.jsxs(Ee,{open:d,onOpenChange:x,children:[e.jsx(Re,{asChild:!0,children:e.jsxs(y,{variant:"outline",className:"w-full justify-between font-normal",children:[e.jsx("span",{className:"truncate text-left",children:f}),e.jsx(Ae,{className:"ml-2 h-4 w-4 shrink-0 opacity-60"})]})}),e.jsxs(Me,{className:`${h} max-w-[92vw] p-0`,align:"start",children:[e.jsx("div",{className:"border-b p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(ue,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(B,{value:p,onChange:m=>o(m.target.value),placeholder:"Buscar...",className:"h-8 pl-8 text-xs"})]})}),e.jsxs("div",{className:"flex items-center justify-between px-2 py-1.5 text-xs",children:[e.jsxs(V,{variant:"secondary",children:[c.length," seleccionados"]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(y,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>r(a.map(m=>m.value)),children:"Todos"}),e.jsx(y,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>r([]),children:"Ninguno"})]})]}),e.jsx(Ie,{className:"h-64",children:e.jsxs("div",{className:"p-1",children:[a.length===0&&e.jsx("p",{className:"px-2 py-6 text-center text-xs text-muted-foreground",children:"Sin resultados"}),a.map(m=>e.jsxs("button",{type:"button",onClick:()=>u(m.value),className:"flex w-full items-start gap-2 rounded-md px-2 py-2 text-left hover:bg-muted/60",children:[e.jsx(We,{checked:c.includes(m.value),className:"mt-0.5 pointer-events-none"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-xs font-medium",children:m.label}),m.hint&&e.jsx("span",{className:"block truncate text-[10px] text-muted-foreground",children:m.hint})]})]},m.value))]})})]})]})]})}function is({events:s,gates:t,draft:l,onDraftChange:c,onSearch:r,onReset:h,loading:d,activeFiltersCount:x}){const p=N.useMemo(()=>(s??[]).map(a=>{const u=a.event_type===pe,f=!u&&a.home_team&&a.away_team?`${a.home_team} vs ${a.away_team}`:a.name,g=a.event_date?A(new Date(a.event_date),"dd MMM yyyy · HH:mm",{locale:he}):"";return{value:a.id,label:f,hint:[u?"PASE":null,g].filter(Boolean).join(" · ")}}),[s]),o=N.useMemo(()=>(t??[]).map(a=>({value:a.id,label:a.name,hint:[a.code,a.is_active===!1?"Inactiva":null].filter(
1Boolean).join(" · ")})),[t]);return e.jsxs("div",{className:"space-y-4 rounded-lg border bg-card p-3 sm:p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs font-medium",children:"Filtros"}),x>0&&e.jsxs(V,{variant:"secondary",children:[x," activos"]})]}),x>0&&e.jsxs(y,{variant:"outline",size:"sm",onClick:h,className:"border-destructive/40 text-destructive hover:border-destructive hover:bg-destructive hover:text-destructive-foreground",children:[e.jsx(Le,{className:"mr-1 h-4 w-4"}),"Limpiar"]})]}),e.jsxs("div",{className:"grid items-start gap-3 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(de,{label:"Eventos",placeholder:"Todos los eventos",options:p,selected:l.eventIds,onChange:a=>c({eventIds:a})}),e.jsx(de,{label:"Puertas",placeholder:"Todas las puertas",options:o,selected:l.gateIds,onChange:a=>c({gateIds:a}),width:"w-[320px]"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(M,{className:"text-xs text-muted-foreground",children:"Resultado"}),e.jsxs(Q,{value:l.result,onValueChange:a=>c({result:a}),children:[e.jsx(K,{children:e.jsx(Y,{})}),e.jsxs(X,{children:[e.jsx(L,{value:"all",children:"Todos"}),e.jsx(L,{value:"allowed",children:"Permitidos"}),e.jsx(L,{value:"denied",children:"Denegados"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(M,{className:"text-xs text-muted-foreground",children:"Tipo de acceso"}),e.jsxs(Q,{value:l.accessType,onValueChange:a=>c({accessType:a}),children:[e.jsx(K,{children:e.jsx(Y,{})}),e.jsxs(X,{children:[e.jsx(L,{value:"all",children:"Todos"}),e.jsx(L,{value:"ticket",children:"Entradas"}),e.jsx(L,{value:"credential",children:"Credenciales"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(M,{className:"text-xs text-muted-foreground",children:"Desde"}),e.jsx(B,{type:"date",value:l.dateFrom,onChange:a=>c({dateFrom:a.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(M,{className:"text-xs text-muted-foreground",children:"Hasta"}),e.jsx(B,{type:"date",value:l.dateTo,onChange:a=>c({dateTo:a.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(M,{className:"text-xs text-muted-foreground",children:"Código"}),e.jsxs("div",{className:"relative",children:[e.jsx(_e,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(B,{value:l.codeSearch,onChange:a=>c({codeSearch:a.target.value}),placeholder:"Código de ticket o QR...",className:"pl-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(M,{className:"text-xs text-muted-foreground",children:"Persona"}),e.jsxs("div",{className:"relative",children:[e.jsx(De,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(B,{value:l.personSearch,onChange:a=>c({personSearch:a.target.value}),placeholder:"Nombre, email o CI...",className:"pl-9"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[e.jsxs(y,{onClick:r,disabled:d,className:"gap-2 rounded-full",children:[e.jsx(ue,{className:"h-4 w-4"}),d?"Buscando...":"Buscar"]}),e.jsx(y,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{const a=A(new Date,"yyyy-MM-dd");c({dateFrom:a,dateTo:a})},children:"Hoy"}),e.jsx(y,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{const a=new Date,u=new Date;u.setDate(u.getDate()-6),c({dateFrom:A(u,"yyyy-MM-dd"),dateTo:A(a,"yyyy-MM-dd")})},children:"Ãltimos 7 dÃas"})]})]})}function H({icon:s,label:t,value:l,tone:c}){return e.jsx(ge,{className:`border-l-4 ${c}`,children:e.jsxs(fe,{className:"flex items-center gap-3 p-4",children:[e.jsx("div",{className:"rounded-md bg-primary/10 p-2",children:e.jsx(s,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:t}),e.jsx("p",{className:"text-xl font-extrabold tabular-nums",children:l.toLocaleStr
1ing("es-BO")})]})]})})}function ls({matrix:s,totals:t,loading:l}){const{sectors:c,ticketTypes:r,counts:h}=s,d=c.length>0&&r.length>0,x=a=>r.reduce((u,f)=>{var g;return u+(((g=h[a])==null?void 0:g[f])??0)},0),p=a=>c.reduce((u,f)=>{var g;return u+(((g=h[f])==null?void 0:g[a])??0)},0),o=c.reduce((a,u)=>a+x(u),0);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-5",children:[e.jsx(H,{icon:Ce,label:"Escaneos",value:t.total,tone:"border-l-primary"}),e.jsx(H,{icon:Pe,label:"Permitidos",value:t.allowed,tone:"border-l-emerald-500"}),e.jsx(H,{icon:Je,label:"Denegados",value:t.denied,tone:"border-l-red-400"}),e.jsx(H,{icon:le,label:"Ãnicos",value:t.unique,tone:"border-l-sky-500"}),e.jsx(H,{icon:es,label:"Reingresos",value:t.reentries,tone:"border-l-amber-500"})]}),e.jsxs(ge,{children:[e.jsx(Fe,{className:"pb-3",children:e.jsxs(Oe,{className:"flex items-center gap-2 text-sm font-bold tracking-tight",children:[e.jsx("div",{className:"rounded-md bg-primary/10 p-1.5",children:e.jsx(le,{className:"h-3.5 w-3.5 text-primary"})}),"Accesos permitidos por sector y tipo"]})}),e.jsx(fe,{children:l?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"Cargando..."}):d?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(be,{children:[e.jsx(ye,{children:e.jsxs(z,{children:[e.jsx(T,{className:"min-w-[180px]",children:"Sector"}),r.map(a=>e.jsx(T,{className:"whitespace-nowrap text-right",children:a},a)),e.jsx(T,{className:"whitespace-nowrap text-right",children:"Total"})]})}),e.jsx(we,{children:c.map(a=>e.jsxs(z,{children:[e.jsx(S,{className:"font-medium",children:a}),r.map(u=>{var g;const f=((g=h[a])==null?void 0:g[u])??0;return e.jsx(S,{className:`text-right tabular-nums ${f===0?"text-muted-foreground/50":""}`,children:f.toLocaleString("es-BO")},u)}),e.jsx(S,{className:"text-right font-bold tabular-nums text-emerald-500",children:x(a).toLocaleString("es-BO")})]},a))}),e.jsx("tfoot",{className:"border-t border-border/60 bg-muted/30",children:e.jsxs("tr",{children:[e.jsx("td",{className:"p-3 text-xs font-bold uppercase tracking-wider",children:"Total"}),r.map(a=>e.jsx("td",{className:"p-3 text-right font-bold tabular-nums",children:p(a).toLocaleString("es-BO")},a)),e.jsx("td",{className:"p-3 text-right font-bold tabular-nums text-emerald-500",children:o.toLocaleString("es-BO")})]})})]})}):e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"Sin datos para los filtros seleccionados"})})]})]})}function Z(s){return s&&{IDENTITY_NOT_FOUND:"Código no encontrado para este evento",TICKET_WRONG_EVENT:"El código no pertenece a este evento",TICKET_CANCELLED:"Ticket cancelado",TICKET_BANNED:"La entrada está bloqueada",QR_INVALID:"El código QR no es válido",QR_EXPIRED:"El código QR expiró, solicita uno nuevo",NO_QR_CODE:"La credencial no tiene un código QR asignado",CREDENTIAL_INACTIVE:"La credencial no está activa",CREDENTIAL_FROZEN:"La credencial está congelada",CREDENTIAL_EXPIRED:"La credencial expiró",MEMBERSHIP_INACTIVE:"La membresÃa no está activa",OVERDUE_PAYMENTS:"El abono está en mora: tiene cuotas vencidas",TICKET_ALREADY_USED:"La entrada ya fue utilizada para ingresar",MEMBERSHIP_ALREADY_USED:"El abono ya registró un acceso a este evento (QR o NFC)"}[s]||"Acceso denegado"}function me(s,t){const c=!!t&&(s.result==="denied"||s.result==="warning"||s.denialReason)?"cursor-pointer":"";return s.result==="allowed"?e.jsx(V,{className:"border-emerald-500/30 bg-emerald-500/15 text-emerald-500",children:"Permitido"}):s.result==="denied"?e.jsx(V,{title:s.denialReason?"Ver motivo":void 0,onClick:t,className:`border-red-500/30 bg-red-500/15 text-red-400 ${c}`,children:"Denegado"}):e.jsx(V,{variant:"secondary",className:c,children:s.result})}function xe(s){return s==="qr"?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-blue-500/30 bg-blue-500/15 px-2 py-0.5 text-xs text-blue-400",children:[e.jsx(_e,{className:"h-3 w-3"}),"QR"]}):s==="nfc"?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-violet-500/30 bg-violet-500/15 px-2 py-0.5 text-xs text-violet-400",children:[e.jsx(ts,{className:"h-3 w-3"}),"NFC"]}):s==="rfid"?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-amber-500/30 bg-amber-500/15 px-2 py-0.5 text-xs text-amber-400",children:[e.jsx(ns,{className:"h-3 w-3"}),"RFID"]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"â"})}function rs({rows:s,loading:t,eventLabels:l={},onRevoked:c}){const[r,h]=N.useState(20),[d,x]=N.useState(0),[p,o]=N.useState("allowed"),{isAdmin:a}=je(),[u,f]=N.useState(null),[g,m]=N.useState(null),[b,C]=N.useState(""),[k,w]=N.useState(!1),v=a,j=v?12:11,E=async()=>
1{if(!u)return;const i=b.trim();if(i.length<5){D.error("Indica un motivo de al menos 5 caracteres");return}w(!0);try{const{error:q}=await I.rpc("admin_revoke_access_log",{p_log_id:u.id,p_reason:i.slice(0,500)});if(q)throw q;D.success("Acceso revocado"),f(null),C(""),c==null||c()}catch(q){D.error((q==null?void 0:q.message)||"No se pudo revocar el acceso")}finally{w(!1)}},R=N.useMemo(()=>s.filter(i=>i.result==="allowed"),[s]),n=N.useMemo(()=>s.filter(i=>i.result!=="allowed"),[s]),_=p==="allowed"?R:n,P=_.length,F=Math.max(1,Math.ceil(P/r)),O=Math.min(d,F-1),G=O*r,U=N.useMemo(()=>_.slice(G,G+r),[_,G,r]);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 rounded-lg border bg-card px-3 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-4",children:[e.jsx(ss,{value:p,onValueChange:i=>{o(i),x(0)},children:e.jsxs(as,{children:[e.jsxs(re,{value:"allowed",children:["Permitidos",e.jsx("span",{className:"ml-2 rounded-full bg-emerald-500/15 px-2 text-[11px] text-emerald-500",children:R.length.toLocaleString("es-BO")})]}),e.jsxs(re,{value:"denied",children:["Denegados",e.jsx("span",{className:"ml-2 rounded-full bg-red-500/15 px-2 text-[11px] text-red-400",children:n.length.toLocaleString("es-BO")})]})]})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"font-semibold",children:P.toLocaleString("es-BO")}),e.jsx("span",{className:"text-muted-foreground",children:" escaneos"})]}),e.jsxs(Q,{value:String(r),onValueChange:i=>{h(Number(i)),x(0)},children:[e.jsx(K,{className:"h-9 w-full sm:w-[120px]",children:e.jsx(Y,{})}),e.jsx(X,{children:[10,20,50,100].map(i=>e.jsxs(L,{value:String(i),children:[i," / pág"]},i))})]})]})]}),e.jsx("div",{className:"hidden overflow-x-auto rounded-lg border bg-card lg:block",children:e.jsxs(be,{children:[e.jsx(ye,{children:e.jsxs(z,{className:"text-sm",children:[e.jsx(T,{className:"min-w-[200px] px-2",children:"Evento"}),e.jsx(T,{className:"px-2",children:"Fecha / hora"}),e.jsx(T,{className:"px-2",children:"Persona"}),e.jsx(T,{className:"px-2",children:"Código"}),e.jsx(T,{className:"px-2",children:"Sector"}),e.jsx(T,{className:"px-2",children:"Tipo"}),e.jsx(T,{className:"px-2",children:"Asiento"}),e.jsx(T,{className:"px-2",children:"Puerta"}),e.jsx(T,{className:"px-2",children:"Dispositivo"}),e.jsx(T,{className:"px-2",children:"Medio"}),e.jsx(T,{className:"px-2",children:"Estado"}),v&&e.jsx(T,{className:"px-2",children:"Acción"})]})}),e.jsx(we,{children:t?e.jsx(z,{children:e.jsx(S,{colSpan:j,className:"py-10 text-center text-muted-foreground",children:"Cargando..."})}):U.length===0?e.jsx(z,{children:e.jsx(S,{colSpan:j,className:"py-10 text-center text-muted-foreground",children:"Sin accesos registrados para los filtros aplicados"})}):U.map(i=>e.jsxs(z,{children:[e.jsx(S,{className:"px-2 align-top font-medium",children:i.eventId&&l[i.eventId]||"â"}),e.jsx(S,{className:"whitespace-nowrap px-2 align-top text-xs",children:A(new Date(i.scannedAt),"dd/MM/yyyy HH:mm:ss")}),e.jsxs(S,{className:"px-2 align-top",children:[e.jsx("div",{className:"font-medium",children:i.personName||"â"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.personCi||i.personEmail||"â"})]}),e.jsx(S,{className:"px-2 align-top font-mono text-xs",children:i.ticketCode||i.scannedCode||"â"}),e.jsx(S,{className:"px-2 align-top text-xs",children:i.sector||"â"}),e.jsx(S,{className:"px-2 align-top text-xs",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[i.accessType==="credential"?e.jsx(qe,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(ze,{className:"h-3 w-3 text-muted-foreground"}),i.ticketType||"â"]})}),e.jsx(S,{className:"px-2 align-top text-xs",children:i.seatLabel||"â"}),e.jsxs(S,{className:"px-2 align-top text-xs",children:[i.gateName||"â",i.gateCode&&e.jsx("div",{className:"text-[10px] text-muted-foreground",children:i.gateCode})]}),e.jsxs(S,{className:"px-2 align-top text-xs",children:[i.deviceName||i.deviceCode||i.deviceId||"â",i.syncedOffline&&e.jsx("div",{className:"text-[10px] text-amber-500",children:"Sincronizado offline"})]}),e.jsx(S,{className:"px-2 align-top",children:xe(i.medium)}),e.jsxs(S,{className:"px-2 align-top",children:[me(i,()=>i.denialReason&&m(i)),i.denialReason&&e.jsx("div",{className:"mt-1 text-[10px] text-muted-foreground",children:Z(i.denialReason)})]}),v&&e.jsx(S,{className:"px-2 align-top",children:i.result==="allowed"&&e.jsxs(y,{variant:"outline",size:"sm",className:"h-8 gap-1 border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:()=>{f(i),C("")},children:[e.jsx(oe,{className:"h-3.5 w-3.5"}),"Revocar"]})})]},i.id))})]})}),e.jsxs("div",{className:"space-y-2 lg:hidden",children:[U.map(i=>e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-semibold",children:i.personName||"â"}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:i.eventId&&l[i.eventId]||"â"})]}),me(i,()=>i.denialReason&&m(i)),i.denialReason&&e.jsx("div",{className:"text-[10px] text-muted-foreground text-right",children:Z(i.denialReason)})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-2 text-[11px]",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Código: "}),e.jsx("span",{className:"font-mono",children:i.ticketCode||i.scannedCode||"â"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Fecha: "}),A(new Date(i.scannedAt),"dd/MM/yy HH:mm")]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Sector: "}),i.sector||"â"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Tipo: "}),i.ticketType||"â"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Puerta: "}),i.gateName||"â"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Asiento: "}),i.seatLabel||"â"]})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 text-[11px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Medio:"}),xe(i.medium)]}),v&&i.result==="allowed"&&e.jsxs(y,{variant:"outline",size:"sm",className:"h-8 gap-1 border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:()=>{f(i),C("")},children:[e.jsx(oe,{className:"h-3.5 w-3.5"}),"Revocar"]})]})]},i.id)),!t&&U.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"Sin accesos registrados"})]}),F>1&&e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-card px-3 py-2",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Página ",O+1," de ",F]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(y,{variant:"outline",size:"sm",disabled:O===0,onClick:()=>x(O-1),children:e.jsx(He,{className:"h-4 w-4"})}),e.jsx(y,{variant:"outline",size:"sm",disabled:O>=F-1,onClick:()=>x(O+1),children:e.jsx($e,{className:"h-4 w-4"})})]})]}),e.jsx(J,{open:!!u,onOpenChange:i=>
1{!i&&!k&&(f(null),C(""))},children:e.jsxs(ee,{className:"sm:max-w-md",children:[e.jsxs(se,{children:[e.jsx(ae,{children:"Revocar acceso"}),e.jsx(te,{children:"Se limpiará el ingreso registrado y el escaneo dejará de figurar en el control de accesos. Esta acción queda auditada."})]}),u&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-xs",children:[e.jsx("div",{className:"font-medium",children:u.personName||"Sin nombre"}),e.jsx("div",{className:"font-mono text-muted-foreground",children:u.ticketCode||u.scannedCode||"â"}),e.jsxs("div",{className:"text-muted-foreground",children:[u.sector||"â"," · ",A(new Date(u.scannedAt),"dd/MM/yyyy HH:mm:ss")]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(M,{htmlFor:"revoke-reason",children:"Motivo de la revocación *"}),e.jsx(Se,{id:"revoke-reason",value:b,maxLength:500,rows:3,placeholder:"Ej: ingreso registrado por error del lector",onChange:i=>C(i.target.value)}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[b.trim().length,"/500 caracteres"]})]})]}),e.jsxs(ne,{children:[e.jsx(y,{variant:"outline",disabled:k,onClick:()=>f(null),children:"Cancelar"}),e.jsxs(y,{variant:"destructive",disabled:k||b.trim().length<5,onClick:E,children:[k&&e.jsx(ve,{className:"mr-2 h-4 w-4 animate-spin"}),"Revocar acceso"]})]})]})}),e.jsx(J,{open:!!g,onOpenChange:i=>{i||m(null)},children:e.jsxs(ee,{className:"sm:max-w-md",children:[e.jsxs(se,{children:[e.jsx(ae,{children:"Acceso denegado"}),e.jsx(te,{children:"Motivo del rechazo registrado en el control de accesos."})]}),g&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-xs",children:[e.jsx("div",{className:"font-medium",children:g.personName||"Sin nombre"}),e.jsx("div",{className:"font-mono text-muted-foreground",children:g.ticketCode||g.scannedCode||"â"}),e.jsxs("div",{className:"text-muted-foreground",children:[g.sector||"â"," · ",A(new Date(g.scannedAt),"dd/MM/yyyy HH:mm:ss")]})]}),e.jsx("div",{className:"rounded-md border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-100",children:Z(g.denialReason)}),g.denialReason&&e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["Código interno: ",g.denialReason]})]}),e.jsx(ne,{children:e.jsx(y,{variant:"outline",onClick:()=>m(null),children:"Cerrar"})})]})})]})}function os({events:s,eventLabels:t,defaultEventId:l,onDone:c}){const[r,h]=N.useState(!1),[d,x]=N.useState(l??""),[p,o]=N.useState(""),[a,u]=N.useState(!1),f=d?t[d]||"Evento seleccionado":"",g=async()=>{if(!d){D.error("Selecciona el evento a limpiar");return}u(!0);try{const{data:m,error:b}=await I.rpc("admin_purge_event_access",{p_event_id:d,p_reason:p.trim().slice(0,500)||null});if(b)throw b;const C=m??{};D.success(`Limpieza ejecutada: ${C.cleared_logs??0} escaneos, ${C.cleared_tickets??0} entradas y ${C.cleared_external??0} códigos externos restablecidos`),h(!1),o(""),c==null||c()}catch(m){D.error((m==null?void 0:m.message)||"No se pudo limpiar los accesos del evento")}finally{u(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>{x(l??""),o(""),h(!0)},className:"gap-2 rounded-full border-red-500/30 text-red-400 hover:bg-red-500/10",children:[e.jsx(Be,{className:"h-4 w-4"}),"Limpiar accesos"]}),e.jsx(J,{open:r,onOpenChange:m=>{a||h(m)},children:e.jsxs(ee,{className:"sm:max-w-lg",children:[e.jsxs(se,{children:[e.jsxs(ae,{className:"flex items-center gap-2",children:[e.jsx(Ne,{className:"h-5 w-5 text-amber-500"}),"Limpiar accesos del evento"]}),e.jsx(te,{children:"Se revocarán todos los ingresos registrados del evento seleccionado y las entradas quedarán disponibles para ingresar de nuevo. No afecta a ningún otro evento y queda auditado."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(M,{children:"Evento *"}),e.jsxs(Q,{value:d,onValueChange:x,disabled:a,children:[e.jsx(K,{children:e.jsx(Y,{placeholder:"Selecciona un evento"})}),e.jsx(X,{className:"max-h-72",children:s.map(m=>e.jsx(L,{value:m.id,children:t[m.id]||m.id},m.id))})]})]}),d&&e.jsxs("div",{className:"rounded-md border border-red-500/30 bg-red-500/10 p-3 text-sm",children:["Se limpiarán únicamente los accesos de: ",e.jsx("span",{className:"font-semibold",children:f})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(M,{htmlFor:"purge-reason",children:"Motivo (opcional)"}),e.jsx(Se,{id:"purge-reason",value:p,maxLength:500,rows:3,placeholder:"Ej: limpieza posterior a las pruebas de configuración",onChange:m=>o(m.target.value),disabled:a})]})]}),e.jsxs(ne,{children:[e.jsx(y,{variant:"outline",disabled:a,onClick:()=>h(!1),children:"Cancelar"}),e.jsxs(y,{variant:"destructive",disabled:a||!d,onClick:g,children:[a&&e.jsx(ve,{className:"mr-2 h-4 w-4 animate-spin"}),"Confirmar limpieza"]})]})]})})]})}const $={eventIds:[],gateIds:[],result:"all",accessType:"all",dateFrom:"",dateTo:"",codeSearch:"",personSearch:""};function ds(s){let t=0;return s.eventIds.length&&t++,s.gateIds.length&&t++,s.result!=="all"&&t++,s.accessType!=="all"&&t++,s.dateFrom&&t++,s.dateTo&&t++,s.codeSearch.trim()&&t++,s.personSearch.trim()&&t++,t}const ms=` 2 id, scanned_at, result, denial_reason, direction, scanned_code, synced_offline, metadata, 3 event_id, ticket_id, credential_id, family_profile_id, device_id, 4 tickets:ticket_id ( ticket_code, seat_id, seatsio_object_label, is_courtesy, metadata ), 5 stadium_gates:gate_id ( name, code ), 6 access_devices:device_id ( name, device_code ), 7 member_credentials:credential_id ( credential_type, status ), 8 family_profiles:family_profile_id ( full_name, email, ci_number,
8ci_complement, ci_expedition ) 9`;function xs(s){if(!(s!=null&&s.ci_number))return null;const t=s.ci_complement?`-${s.ci_complement}`:"",l=s.ci_expedition?` ${s.ci_expedition}`:"";return`${s.ci_number}${t}${l}`.trim()}function us(s,t,l,c){var g,m,b,C,k,w,v,j,E;const r=s.tickets,h=cs(r==null?void 0:r.seat_id),d=(r==null?void 0:r.metadata)||{},x=s.metadata||{},p=(x.membership_id?t==null?void 0:t.get(x.membership_id):void 0)??(s.scanned_code?l==null?void 0:l.get(String(s.scanned_code).toUpperCase()):void 0),o=!r&&s.scanned_code?c==null?void 0:c.get(String(s.scanned_code).toUpperCase()):void 0,a=s.ticket_id||o?"ticket":s.credential_id?"credential":"otro",u=["qr","nfc","rfid"].includes(x.medium)?x.medium:null,f=r?r.is_courtesy?"CortesÃa":d.tier_name||d.ticket_type||"Entrada":o!=null&&o.ticketType?o.ticketType:p!=null&&p.typeName?p.typeName:s.credential_id?((g=s.member_credentials)==null?void 0:g.credential_type)==="physical"?"Credencial fÃsica":"Credencial digital":o?"Entrada":"â";return{id:s.id,scannedAt:s.scanned_at,result:s.result??"unknown",denialReason:s.denial_reason??null,direction:s.direction??null,scannedCode:s.scanned_code??null,eventId:s.event_id??null,gateName:((m=s.stadium_gates)==null?void 0:m.name)??null,gateCode:((b=s.stadium_gates)==null?void 0:b.code)??null,deviceName:((C=s.access_devices)==null?void 0:C.name)??null,deviceCode:((k=s.access_devices)==null?void 0:k.device_code)??null,deviceId:((w=s.metadata)==null?void 0:w.device_id)??s.device_id??null,accessType:a,medium:u,personName:((v=s.family_profiles)==null?void 0:v.full_name)??(o==null?void 0:o.name)??null,personEmail:((j=s.family_profiles)==null?void 0:j.email)??null,personCi:xs(s.family_profiles)??(o==null?void 0:o.ci)??null,ticketCode:(r==null?void 0:r.ticket_code)??(o?s.scanned_code??null:null),sector:d.sector_name??(o==null?void 0:o.sectorName)??(p==null?void 0:p.sectorName)??(a==="credential"?"Credenciales":null),ticketType:f,seatLabel:(r==null?void 0:r.seatsio_object_label)||h.seatLabel||(o==null?void 0:o.seatLabel)||(p==null?void 0:p.seatLabel)||null,credentialType:((E=s.member_credentials)==null?void 0:E.credential_type)??null,syncedOffline:s.synced_offline??null}}const Te=`id, qr_code, seatsio_object_label, subscription_type_id, combo_subscription_type_id, 10 sector:sectors!memberships_sector_id_fkey ( name ), 11 subscription_type:subscription_types!memberships_subscription_type_id_fkey ( name ), 12 seat:seats!memberships_seat_id_fkey ( label )`;async function ke(s){var h,d,x,p;const t=new Map,l=Array.from(new Set(s.flatMap(o=>[o.subscription_type_id,o.combo_subscription_type_id]).filter(Boolean))),c=new Map,r=new Map;if(l.length){const[{data:o},{data:a}]=await Promise.all([I.from("subscription_types").select("id, name").in("id",l),I.from("subscription_type_sectors").select("subscription_type_id, sector:sectors ( name )").in("subscription_type_id",l)]);for(const f of o??[])f.name&&c.set(f.id,f.name);const u=new Map;for(const f of a??[]){const g=(h=f.sector)==null?void 0:h.name;
12g&&(u.has(f.subscription_type_id)||u.set(f.subscription_type_id,new Set),u.get(f.subscription_type_id).add(g))}for(const[f,g]of u)g.size===1&&r.set(f,Array.from(g)[0])}for(const o of s){const a=o.subscription_type_id??o.combo_subscription_type_id??null,u={sectorName:((d=o.sector)==null?void 0:d.name)??(a?r.get(a)??null:null),typeName:((x=o.subscription_type)==null?void 0:x.name)??(a?c.get(a):null)??"Abono",seatLabel:o.seatsio_object_label||((p=o.seat)==null?void 0:p.label)||null};t.set(o.id,u),o.qr_code&&t.set(String(o.qr_code).toUpperCase(),u)}return t}const ps=200;function ie(s,t=ps){const l=[];for(let c=0;c<s.length;c+=t)l.push(s.slice(c,c+t));return l}async function hs(s){if(!s.length)return{map:new Map,failed:!1};const t=await Promise.all(ie(s).map(r=>I.from("memberships").select(Te).in("id",r))),l=t.some(r=>r.error),c=t.flatMap(r=>r.data??[]);return{map:await ke(c),failed:l}}async function gs(s){if(!s.length)return{map:new Map,failed:!1};const t=await Promise.all(ie(s).map(r=>I.from("memberships").select(Te).in("qr_code",r))),l=t.some(r=>r.error),c=t.flatMap(r=>r.data??[]);return{map:await ke(c),failed:l}}async function fs(s,t=[]){const l=new Map;if(!s.length)return{map:l,failed:!1};let c=!1;const r=await Promise.all(ie(s).map(h=>{const d=h.map(p=>`"${p.replace(/"/g,"")}"`).join(",");let x=I.from("todotix_access_tickets").select("qr_code, public_code, rfid_code, name, ci_number, sector_name, ticket_type, sector_seat_id, table_id").or(`qr_code.in.(${d}),public_code.in.(${d}),rfid_code.in.(${d})`);return t.length&&(x=x.in("ticketing_event_id",t)),x}));for(const h of r){if(h.error){c=!0;continue}for(const d of h.data??[]){const x={name:d.name||null,ci:d.ci_number||null,sectorName:d.sector_name||null,ticketType:d.ticket_type||null,seatLabel:d.sector_seat_id||d.table_id||null};for(const p of[d.qr_code,d.public_code,d.rfid_code])p&&l.set(String(p).toUpperCase(),x)}}return{map:l,failed:c}}function js(s){const t={},l=new Set,c=new Set;for(const r of s){if(r.result!=="allowed")continue;const h=r.sector||"Sin sector",d=r.ticketType||"Sin tipo";l.add(h),c.add(d),t[h]=t[h]||{},t[h][d]=(t[h][d]??0)+1}return{sectors:Array.from(l).sort((r,h)=>r.localeCompare(h)),ticketTypes:Array.from(c).sort((r,h)=>r.localeCompare(h)),counts:t}}function vs(s,t){return ce({queryKey:["access-report",s],enabled:t,staleTime:3e4,queryFn:async()=>{let l=I.from("access_logs").select(ms).order("scanned_at",{ascending:!1}).limit(5e3);s.eventIds.length&&(l=l.in("event_id",s.eventIds)),s.gateIds.length&&(l=l.in("gate_id",s.gateIds)),s.result!=="all"&&(l=l.eq("result",s.result)),s.accessType==="ticket"&&(l=l.not("ticket_id","is",null)),s.accessType==="credential"&&(l=l.not("credential_id","is",null)),s.dateFrom&&(l=l.gte("scanned_at",new Date(`${s.dateFrom}T00:00:00`).toISOString())),s.dateTo&&(l=l.lte("scanned_at",new Date(`${s.dateTo}T23:59:59`).toISOString()));const{data:c,error:r}=await l;if(r)throw r;const h=n=>{const _=(n==null?void 0:n.metadata)||{};if(_.revoked_at||_.action==="revoke_access"||_.action==="clear_access")return!0;const P=String((n==null?void 0:n.denial_reason)??"").toUpperCase();return P.includes("REVOKED")||P.includes("REVOCA")},d=(c??[]).filter(n=>!h(n)),x=Array.from(new Set((d??[]).map(n=>{var _;return(_=n.metadata)==null?void 0:_.membership_id}).filter(n=>typeof n=="string"&&n.length>0))),p=[],o=await hs(x),a=o.map,u=Array.from(new Set((d??[]).filter(n=>{var _;return!n.ticket_id&&!n.credential_id&&!((_=n.metadata)!=null&&_.membership_id)&&n.scanned_code}).map(n=>String(n.scanned_code).toUpperCase()))),f=await gs(u),g=f.map,m=new Set(Array.from(g.keys()).map(n=>n.toUpperCase()));(o.failed||f.failed)&&p.push("No se pudieron completar los datos de algunos socios/abonos;
12 el sector puede figurar como 'Sin sector'. Presiona Actualizar.");const b=u.filter(n=>!m.has(n)),C=await fs(b,s.eventIds),k=C.map;C.failed&&p.push("No se pudieron completar los datos de algunas entradas de Todotix; el sector puede figurar como 'Sin sector'. Presiona Actualizar.");let w=(d??[]).map(n=>us(n,a,g,k));const v=s.codeSearch.trim().toLowerCase();v&&(w=w.filter(n=>(n.ticketCode??"").toLowerCase().includes(v)||(n.scannedCode??"").toLowerCase().includes(v)));const j=s.personSearch.trim().toLowerCase();j&&(w=w.filter(n=>(n.personName??"").toLowerCase().includes(j)||(n.personEmail??"").toLowerCase().includes(j)||(n.personCi??"").toLowerCase().includes(j)));const E=w.filter(n=>n.result==="allowed"),R=new Set(E.map(n=>n.ticketCode||n.scannedCode||n.id));return{rows:w,warnings:p,matrix:js(w),totals:{total:w.length,allowed:E.length,denied:w.filter(n=>n.result==="denied").length,unique:R.size,reentries:Math.max(0,E.length-R.size)}}}})}function Ns(){return ce({queryKey:["access-report","events"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:t}=await I.from("ticketing_events").select("id, name, home_team, away_team, event_date, event_type").order("event_date",{ascending:!1}).limit(300);if(t)throw t;return s??[]}})}function _s(){return ce({queryKey:["access-report","gates"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:t}=await I.from("stadium_gates").select("id, name, code, is_active").order("sort_order",{ascending:!0});if(t)throw t;return s??[]}})}function zs(){var k,w;const{isAdmin:s}=je(),[t,l]=N.useState($),[c,r]=N.useState($),{data:h=[]}=Ns(),{data:d=[]}=_s(),{data:x,isFetching:p,refetch:o}=vs(c??$,!!c),a=N.useMemo(()=>{const v={};for(const j of h){const R=!(j.event_type===pe)&&j.home_team&&j.away_team?`${j.home_team} vs ${j.away_team}`:j.name,n=j.event_date?A(new Date(j.event_date),"dd MMM yyyy · HH:mm",{locale:he}):"";v[j.id]=n?`${R} â ${n}`:R}return v},[h]),u=N.useMemo(()=>ds(c??t),[c,t]),f=(x==null?void 0:x.rows)??[],g=v=>l(j=>({...j,...v})),m=()=>r({...t}),b=()=>{l($),r($)},C=()=>{if(f.length===0){D.error("No hay accesos para exportar");return}const v=f.map(n=>{var _;return{Evento:n.eventId&&a[n.eventId]||"","Fecha / hora":A(new Date(n.scannedAt),"dd/MM/yyyy HH:mm:ss"),Persona:n.personName??"",CI:n.personCi??"",Email:n.personEmail??"",Código:n.ticketCode??n.scannedCode??"",Sector:n.sector??"",Tipo:n.ticketType??"",Asiento:n.seatLabel??"",Puerta:n.gateName??"",Dispositivo:n.deviceName??n.deviceCode??n.deviceId??"",Medio:((_=n.medium)==null?void 0:_.toUpperCase())??"",Resultado:n.result==="allowed"?"Permitido":n.result==="denied"?"Denegado":n.result,Motivo:n.denialReason??"",Sentido:n.direction??""}}),j=W.json_to_sheet(v),E=Object.keys(v[0]);j["!cols"]=E.map(n=>{let _=n.length;for(const P of v){const F=String(P[n]??"");F.length>_&&(_=F.length)}return{wch:Math.min(_+2,45)}});const R=W.book_new();W.book_append_sheet(R,j,"Accesos"),Ge(R,`control-accesos-${A(new Date,"yyyyMMdd-HHmm")}.xlsx`),D.success("Excel generado")};return e.jsx(Ve,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"hidden shrink-0 rounded-xl bg-primary/10 p-2.5 sm:flex",children:e.jsx(Ce,{className:"h-7 w-7 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"truncate text-xl font-bold tracking-tight sm:text-2xl",children:"Control de Accesos"}),e.jsx("p",{className:"truncate text-xs text-muted-foreground sm:text-sm",children:"Check-ins de entradas y credenciales por sector, puerta y dispositivo"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:items-center",children:[s&&e.jsx(os,{events:h,eventLabels:a,defaultEventId:((k=c==null?void 0:c.eventIds)==null?void 0:k.length)===1?c.eventIds[0]:null,onDone:()=>o()}),e.jsxs(y,{variant:"outline",size:"sm",onClick:C,className:"gap-2 rounded-full",children:[e.jsx(Ue,{className:"h-4 w-4"}),"Excel"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>o(),disabled:p,className:"gap-2 rounded-full",children:[e.jsx(Qe,{className:`h-4 w-4 ${p?"animate-spin":""}`}),"Actualizar"]})]})]}),e.jsx(is,{events:h,gates:d,draft:t,onDraftChange:g,onSearch:m,onReset:b,loading:p,activeFiltersCount:u}),(((w=x==null?void 0:x.warnings)==null?void 0:w.length)??0)>0&&e.jsxs(Ke,{variant:"destructive",children:[e.jsx(Ne,{className:"h-4 w-4"}),e.jsx(Ye,{children:"Datos incompletos"}),e.jsx(Xe,{children:x.warnings.map(v=>e.jsx("div",{children:v},v))})]}),e.jsx(ls,{matrix:(x==null?void 0:x.matrix)??{sectors:[],ticketTypes:[],counts:{}},totals:(x==null?void 0:x.totals)??{total:0,allowed:0,denied:0,unique:0,reentries:0},loading:p}),e.jsx(rs,{rows:f,loading:p,eventLabels:a,onRevoked:()=>o()})]})})}export{zs 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.