PageSourceSearch

https://irpa2026colombia.org/assets/SystemConfigAdmin-BH-WJQ-_.js

js irpa2026colombia.org collected 2026-10-08 03:17:06 UTC 79,103 bytes, 36 lines download raw bytes

1import{c as ns,d as ce,r as a,s as N,j as e,b as R,B as C,X as js,g as gs,e as fs,u as vs}from"./index-DnVm687U.js";import{C as Ns,H as bs,F as ys}from"./Footer-Bvqa_r8G.js";import{T as _s,a as Cs,b as ae,c as re}from"./tabs-DbatMKTI.js";import{I as U}from"./input-D4ugazI8.js";import{L as _}from"./label-BWZGrcrB.js";import{C as G,a as H,b as X,c as J,d as Z}from"./card-CRFaJYNz.js";import{R as ws,a as es}from"./radio-group-CcBF0RkW.js";import{B as Y}from"./badge-BLNB1n0H.js";import{F as ue}from"./file-text-BU0yiu-Q.js";import{E as Ss}from"./eye-Bub6U8nG.js";import{D as Oe}from"./download-Cln34tJJ.js";import{T as we}from"./trash-2-mVbNQiFx.js";import{E as Es}from"./external-link-DgRNJBvk.js";import{U as $e}from"./upload-0ilaCe4N.js";import{P as ls,c as ks,a as Ps,g as Ds}from"./brotherPrinterService-DvFgUYk-.js";import{C as z}from"./checkbox-DQGP46Z3.js";import{S as ss}from"./separator-Cey6I7pC.js";import{S as ge,a as fe,b as ve,c as Ne,d as W}from"./select-BBeLgipb.js";import{C as Fs,S as Ls}from"./scale-CUfZvnq6.js";import{R as cs}from"./refresh-cw-Idxe6BZk.js";import{C as ze}from"./circle-alert-DRJhAiAk.js";import{S as os}from"./settings-wck-US1o.js";import{S as Le}from"./save-N9WwdXh1.js";import{C as he}from"./circle-check-CEudxvXQ.js";import{C as Is}from"./circle-x-DIo5bdqO.js";import{T as Be}from"./textarea-wowC9C90.js";import{T as Se,a as Ee,b as te,c as M,d as ke,e as I}from"./table-DWz2i9MN.js";import{P as As}from"./password-input-D-fF6IPs.js";import{D as Ie,b as Ae,c as Re,d as Te,e as as,f as rs,a as Rs}from"./dialog-BQOPzVNo.js";import{A as Ue,b as Ge,c as He,d as Ve,e as Qe,f as Ke,g as Xe,h as Je,a as Ts}from"./alert-dialog-RI-hpkS0.js";import{U as We}from"./users-qgl9wAWj.js";import{P as ds}from"./plus-Bh0gLK_k.js";import{f as je}from"./format-BeKxgCCE.js";import{e as Me}from"./es-CFK9b-z2.js";import{A as be,b as ye,a as _e}from"./alert-CuNsnv7-.js";import{S as Ce}from"./send-BBcX3eXP.js";import{I as ms}from"./info-zLLFQJ0e.js";import{u as Ms,a as Pe,K as us}from"./useMutation-2Rg_4lIw.js";import{S as qs}from"./switch-BVLlnVxk.js";import{C as Os}from"./clock-CIC8GvrU.js";import{C as De}from"./circle-check-big-hO1idMQN.js";import{M as qe}from"./mail-BBtFmBsn.js";import{D as $s}from"./database-CIOqq618.js";import{H as hs,U as zs}from"./user-x-kpRAOZAB.js";import{T as Bs}from"./triangle-alert-DrFwYdXz.js";import{S as xs}from"./search-BNZJvCG8.js";import{u as Fe,w as Us}from"./xlsx-DjuO7_Ju.js";import{F as Gs}from"./filter-D0S6FpMe.js";import{S as Hs,a as Vs}from"./scroll-area-ClfoZ0EB.js";import{A as Qs}from"./arrow-left-i1Qu9EeE.js";import{R as Ks}from"./receipt-CQodndI6.js";import{S as Xs}from"./shield-BN1RiLGr.js";import"./dropdown-menu-elZyZctl.js";import"./index-B-Wc5f3e.js";import"./Combination-D1NCdNup.js";import"./index-C7OIboLl.js";import"./log-out-CtUQRbPX.js";import"./index-Cue5PJE5.js";import"./chevron-up-46FaISor.js";import"./eye-off-BgwrI24M.js";import"./index-yRo4nqrX.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const Js=ns("Link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]]);/**
7 * @license lucide-react v0.462.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const Ws=ns("TestTube",[["path",{d:"M14.5 2v17.5c0 1.4-1.1 2.5-2.5 2.5c-1.4 0-2.5-1.1-2.5-2.5V2",key:"125lnx"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M14.5 16h-5",key:"1ox875"}]]),ts=({documentType:o,title:j,description:A})=>{const{toast:h}=ce(),[P,L]=a.useState(!0),[D,d]=a.useState(!1),[x,y]=a.useState(null),[w,E]=a.useState("file"),[g,l]=a.useState(""),[p,v]=a.useState(null);a.useEffect(()=>{O()},[o]);const O=async()=>
11{try{L(!0);const{data:c,error:f}=await N.from("legal_documents").select("*").eq("document_type",o).maybeSingle();if(f)throw f;c&&(y(c),E(c.is_external_link?"link":"file"),c.is_external_link&&c.file_url&&l(c.file_url))}catch(c){console.error("Error fetching document:",c)}finally{L(!1)}},T=c=>{var F;const f=(F=c.target.files)==null?void 0:F[0];if(f){if(f.size>10*1024*1024){h({title:"Archivo muy grande",description:"El archivo debe ser menor a 10MB",variant:"destructive"});return}if(f.type!=="application/pdf"){h({title:"Formato inválido",description:"Solo se permiten archivos PDF",variant:"destructive"});return}v(f)}},$=async()=>{if(w==="file"&&!p){h({title:"Archivo requerido",description:"Seleccione un archivo PDF para subir",variant:"destructive"});return}if(w==="link"&&!g){h({title:"URL requerida",description:"Ingrese una URL válida",variant:"destructive"});return}try{d(!0);let c=g,f=null,F=null;if(w==="file"&&p){x!=null&&x.file_url&&!x.is_external_link&&await N.storage.from("legal-documents").remove([x.file_url]);const K=p.name.split(".").pop(),u=`${o}/${Date.now()}.${K}`,{error:i}=await N.storage.from("legal-documents").upload(u,p);if(i)throw i;const{data:r}=N.storage.from("legal-documents").getPublicUrl(u);c=r.publicUrl,f=p.name,F=p.size}const{error:Q}=await N.from("legal_documents").upsert({document_type:o,file_url:c,is_external_link:w==="link",file_name:f,file_size:F},{onConflict:"document_type"});if(Q)throw Q;h({title:"Documento guardado",description:"El documento se ha guardado correctamente"}),v(null),O()}catch(c){console.error("Error saving document:",c),h({title:"Error",description:c.message||"No se pudo guardar el documento",variant:"destructive"})}finally{d(!1)}},B=async()=>{if(x)try{if(d(!0),!x.is_external_link&&x.file_url){const f=x.file_url.split("/").pop();f&&await N.storage.from("legal-documents").remove([`${o}/${f}`])}const{error:c}=await N.from("legal_documents").delete().eq("id",x.id);if(c)throw c;h({title:"Documento eliminado",description:"El documento se ha eliminado correctamente"}),y(null),l(""),v(null)}catch(c){console.error("Error deleting document:",c),h({title:"Error",description:"No se pudo eliminar el documento",variant:"destructive"})}finally{d(!1)}},t=c=>c<1024?c+" B":c<1024*1024?(c/1024).toFixed(1)+" KB":(c/(1024*1024)).toFixed(1)+" MB";return P?e.jsx(G,{children:e.jsx(H,{className:"flex justify-center items-center py-12",children:e.jsx(R,{className:"w-8 h-8 animate-spin text-primary"})})}):e.jsxs(G,{children:[e.jsxs(X,{children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(ue,{className:"w-5 h-5"}),j]}),e.jsx(Z,{children:A})]}
11),e.jsxs(H,{className:"space-y-6",children:[(x==null?void 0:x.file_url)&&e.jsx("div",{className:"bg-muted/50 rounded-lg p-4 space-y-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ue,{className:"w-8 h-8 text-red-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:x.file_name||"Documento PDF"}),e.jsx("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:x.is_external_link?e.jsxs(Y,{variant:"outline",className:"text-xs",children:[e.jsx(Js,{className:"w-3 h-3 mr-1"}),"Enlace externo"]}):x.file_size&&e.jsx("span",{children:t(x.file_size)})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(C,{variant:"outline",size:"sm",onClick:()=>window.open(x.file_url,"_blank"),children:[e.jsx(Ss,{className:"w-4 h-4 mr-1"}),"Ver"]}),e.jsx(C,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:x.file_url,download:!0,target:"_blank",children:[e.jsx(Oe,{className:"w-4 h-4 mr-1"}),"Descargar"]})}),e.jsx(C,{variant:"destructive",size:"sm",onClick:B,disabled:D,children:e.jsx(we,{className:"w-4 h-4"})})]})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(_,{children:"Tipo de documento"}),e.jsxs(ws,{value:w,onValueChange:c=>E(c),className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(es,{value:"file",id:`file-${o}`}),e.jsx(_,{htmlFor:`file-${o}`,className:"cursor-pointer",children:"Subir archivo PDF"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(es,{value:"link",id:`link-${o}`}),e.jsx(_,{htmlFor:`link-${o}`,className:"cursor-pointer",children:"Enlace externo"})]})]})]}),w==="file"?e.jsxs("div",{className:"space-y-3",children:[e.jsx(_,{children:"Archivo PDF (máx. 10MB)"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(U,{type:"file",accept:".pdf",onChange:T,className:"flex-1"})}),p&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Seleccionado: ",p.name," (",t(p.size),")"]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(_,{children:"URL del documento"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{type:"url",placeholder:"https://ejemplo.com/documento.pdf",value:g,onChange:c=>l(c.target.value),className:"flex-1"}),g&&e.jsx(C,{variant:"outline",size:"icon",onClick:()=>window.open(g,"_blank"),children:e.jsx(Es,{className:"w-4 h-4"})})]})]}),e.jsx(C,{onClick:$,disabled:D||(w==="file"?!p:!g),className:"w-full",children:D?e.jsxs(e.Fragment,{children:[e.jsx(R,{className:"w-4 h-4 mr-2 animate-spin"}),"Guardando..."]}):e.jsxs(e.Fragment,{children:[e.jsx($e,{className:"w-4 h-4 mr-2"}),x?"Actualizar Documento":"Subir Documento"]})})]})]})},is={include_full_name:{label:"Nombre completo",required:!0},include_document:{label:"Documento"},include_category:{label:"Categoría"},include_modality:{label:"Modalidad"},include_qr_code:{label:"Código QR",required:!0},include_email:{label:"Correo electrónico"},include_phone:{label:"Teléfono"},include_profession:{label:"Profesión"},include_specialty:{label:"Especialidad"},include_country:{label:"País"},include_city:{label:"Ciudad"},include_sponsor:{label:"Entidad/Patrocinador"}},Ys=()=>{const{toast:o}=ce(),[j,A]=a.useState(!0),[h,P]=a.useState(!1),[L,D]=a.useState(!1),[d,x]=a.useState(null),[y,w]=a.useState(""),[E,g]=a.useState(""),[l,p]=a.useState([]),[v,O]=a.useState({bpacExtension:!1,sdkVersion:null,printerConnected:!1,printerName:null,templateFound:!1}),[T,$]=a.useState(!1);a.useEffect(()=>{t(),B()},[]),a.useEffect(()=>{E&&c()},[E]);const B=()=>{const b=`${navigator.userAgent}-${screen.width}x${screen.height}-${new Date().getTimezoneOffset()}`.split("").reduce((S,se)=>(S=(S<<5)-S+se.charCodeAt(0),S&S),0);g(`machine-${Math.abs(b).toString(16)}`)},t=async()=>{try{A(!0);const{data:r,error:b}=await N.from("badge_printer_config").select("*").limit(1).maybeSingle();if(b)throw b;r&&x(r)}catch(r){console.error("Error fetching config:",r)}finally{A(!1)}},c=async()=>{if(E)try{const{data:r,error:b}=await N.from("badge_printer_local").select("printer_name").eq("machine_id",E).maybeSingle();!b&&r&&w(r.printer_name)}catch(r){console.error("Error fetching local printer:",r)}},f=(r,b)=>{var S;if(d){if((S=is[r])!=null&&S.required&&!b){o({title:"Campo requerido",description:"Este campo no se puede desactivar",variant:"destructive"});return}x({...d,[r]:b})}},F=async()=>
11{if(d)try{P(!0);const{error:r}=await N.from("badge_printer_config").update({template_path:d.template_path,include_full_name:d.include_full_name,include_document:d.include_document,include_category:d.include_category,include_modality:d.include_modality,include_qr_code:d.include_qr_code,include_email:d.include_email,include_phone:d.include_phone,include_profession:d.include_profession,include_specialty:d.include_specialty,include_country:d.include_country,include_city:d.include_city,include_sponsor:d.include_sponsor}).eq("id",d.id);if(r)throw r;o({title:"Configuración guardada",description:"La configuración de escarapelas se ha actualizado"})}catch(r){console.error("Error saving config:",r),o({title:"Error",description:"No se pudo guardar la configuración",variant:"destructive"})}finally{P(!1)}},Q=async()=>{if(!(!y.trim()||!E))try{D(!0);const{error:r}=await N.from("badge_printer_local").upsert({machine_id:E,printer_name:y.trim()},{onConflict:"machine_id"});if(r)throw r;o({title:"Impresora guardada",description:"La configuración local se ha guardado para este equipo"})}catch(r){console.error("Error saving local printer:",r),o({title:"Error",description:"No se pudo guardar la configuración local",variant:"destructive"})}finally{D(!1)}},K=async()=>{$(!0);try{if(ks()){const b=await Ps((d==null?void 0:d.template_path)||null,y||null);O(b);const S=await Ds();p(S),b.printerConnected?o({title:"✓ Sistema de impresión listo",description:`Impresora: ${b.printerName}`}):o({title:"Extensión detectada",description:"No se detectó ninguna impresora Brother conectada",variant:"destructive"})}else O({bpacExtension:!1,sdkVersion:null,printerConnected:!1,printerName:y||null,templateFound:!1}),p([]),o({title:"Extensión no detectada",description:"Instale la extensión b-PAC de Brother para imprimir escarapelas",variant:"destructive"})}catch(r){console.error("Error checking printer status:",r),o({title:"Error",description:"No se pudo verificar el estado de la impresora",variant:"destructive"})}finally{$(!1)}},u=async()=>{if(!v.bpacExtension||!v.printerConnected){o({title:"Impresora no disponible",description:"Verifique la conexión antes de imprimir",variant:"destructive"});return}o({title:"Impresión de prueba",description:"Enviando prueba a la impresora..."})},i=({active:r,label:b})=>e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(he,{className:"w-4 h-4 text-green-500"}):e.jsx(Is,{className:"w-4 h-4 text-red-500"}),e.jsx("span",{className:r?"text-green-700":"text-red-700",children:b})]});return j?e.jsx(G,{children:e.jsx(H,{className:"flex justify-center items-center py-12",children:e.jsx(R,{className:"w-8 h-8 animate-spin text-primary"})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(G,{children:[e.jsxs(X,{children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(Fs,{className:"w-5 h-5"}),"Estado del Sistema de Impresión"]}),e.jsx(Z,{children:"Verifica la conexión con el sistema de impresión de escarapelas Brother P-Touch"})]}
11),e.jsxs(H,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Extensión b-PAC"}),e.jsx(i,{active:v.bpacExtension,label:v.bpacExtension?"Instalada":"No detectada"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Versión SDK"}),e.jsx("p",{className:"font-medium",children:v.sdkVersion||"N/A"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Impresora Brother"}),e.jsx(i,{active:v.printerConnected,label:v.printerConnected?"Conectada":"No conectada"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Plantilla"}),e.jsx(i,{active:v.templateFound,label:v.templateFound?"Encontrada":"No encontrada"})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(C,{variant:"outline",onClick:K,disabled:T,children:[T?e.jsx(R,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(cs,{className:"w-4 h-4 mr-2"}),"Verificar conexión"]}),e.jsxs(C,{variant:"outline",onClick:u,disabled:!v.bpacExtension||!v.printerConnected,children:[e.jsx(Ws,{className:"w-4 h-4 mr-2"}),"Imprimir prueba"]}),e.jsx(C,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:"https://support.brother.com/g/s/es/htmldoc/bpac/index.html",target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Oe,{className:"w-4 h-4 mr-2"}),"Descargar extensión b-PAC"]})})]}),e.jsx("div",{className:"bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800 rounded-lg p-3",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ze,{className:"w-5 h-5 text-amber-600 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-amber-800 dark:text-amber-200",children:[e.jsx("p",{className:"font-medium",children:"Requisitos del sistema:"}),e.jsxs("ul",{className:"list-disc list-inside mt-1 space-y-1",children:[e.jsx("li",{children:"Impresora Brother QL (QL-700, QL-800, QL-820NWB, etc.)"}),e.jsx("li",{children:"Extensión b-PAC instalada en Chrome/Edge"}),e.jsx("li",{children:"Software P-touch Editor instalado en el equipo"}),e.jsx("li",{children:"Plantilla .lbx configurada con objetos nombrados (txtName, txtDocument, objQR, etc.)"})]})]})]})})]})]}),e.jsxs(G,{children:[e.jsxs(X,{children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(os,{className:"w-5 h-5"}),"Configuración Local (Este Equipo)"]}),e.jsx(Z,{children:"Configuración específica para este equipo de trabajo"})]}),e.jsx(H,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{children:"Impresora para este PC"}),e.jsxs("div",{className:"flex gap-2",children:[l.length>0?e.jsxs(ge,{value:y,onValueChange:w,children:[e.jsx(fe,{className:"flex-1",children:e.jsx(ve,{placeholder:"Seleccionar impresora..."})}),e.jsx(Ne,{children:l.map(r=>e.jsx(W,{value:r,children:r},r))})]}):e.jsx(U,{placeholder:"Ej: Brother QL-820NWB",value:y,onChange:r=>w(r.target.value),className:"flex-1"}),e.jsx(C,{onClick:Q,disabled:L||!y.trim(),children:L?e.jsx(R,{className:"w-4 h-4 animate-spin"}):e.jsx(Le,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["ID del equipo: ",E||"Generando..."]})]})})]}),e.jsxs(G,{children:[e.jsxs(X,{children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"w-5 h-5"}),"Plantilla de Escarapela (Global)"]}),e.jsx(Z,{children:"Configuración global de la plantilla y campos a imprimir"})]}
11),e.jsxs(H,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{children:"Ruta del Archivo de Plantilla (.lbx)"}),e.jsx(U,{placeholder:"C:/Templates/escarapela-congreso.lbx",value:(d==null?void 0:d.template_path)||"",onChange:r=>d&&x({...d,template_path:r.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"La plantilla debe contener objetos con nombres específicos: txtName, txtDocument, txtCategory, txtCountry, objQR, etc."})]}),e.jsx(ss,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(_,{className:"text-base font-semibold",children:"Campos a Imprimir en Escarapela"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:Object.entries(is).map(([r,{label:b,required:S}])=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(z,{id:r,checked:(d==null?void 0:d[r])??!1,onCheckedChange:se=>f(r,se),disabled:S}),e.jsxs(_,{htmlFor:r,className:"flex items-center gap-1 cursor-pointer",children:[b,S&&e.jsx(Y,{variant:"secondary",className:"text-xs ml-1",children:"Obligatorio"})]})]},r))})]}),e.jsx(ss,{}),e.jsx(C,{onClick:F,disabled:h,className:"w-full",children:h?e.jsxs(e.Fragment,{children:[e.jsx(R,{className:"w-4 h-4 mr-2 animate-spin"}),"Guardando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Le,{className:"w-4 h-4 mr-2"}),"Guardar Plantilla y Campos (Global)"]})})]})]})]})},Zs=()=>{const{toast:o}=ce(),[j,A]=a.useState(!0),[h,P]=a.useState(!1),[L,D]=a.useState(!1),[d,x]=a.useState(null),[y,w]=a.useState("COMPROBANTE DE INSCRIPCIÓN"),[E,g]=a.useState(""),[l,p]=a.useState(""),[v,O]=a.useState(""),[T,$]=a.useState(null),[B,t]=a.useState(!0),[c,f]=a.useState(!0),[F,Q]=a.useState(!1),[K,u]=a.useState(!0),[i,r]=a.useState(!0),[b,S]=a.useState(!1),[se,me]=a.useState(!1),[s,m]=a.useState(!1),[k,ne]=a.useState(!1),[ie,le]=a.useState(!1);a.useEffect(()=>{oe()},[]);const oe=async()=>{try{A(!0);const{data:n,error:V}=await N.from("certificate_config").select("*").limit(1).maybeSingle();if(V)throw V;n&&(x(n),w(n.header_text||"COMPROBANTE DE INSCRIPCIÓN"),g(n.subtitle_text||""),p(n.event_date_location||""),O(n.footer_text||""),$(n.logo_url),t(n.include_name),f(n.include_lastname),Q(n.include_document_type),u(n.include_document_number),r(n.include_category),S(n.include_email),me(n.include_phone),m(n.include_amount),ne(n.include_currency),le(n.include_registration_date))}catch(n){console.error("Error fetching config:",n),o({title:"Error",description:"No se pudo cargar la configuración",variant:"destructive"})}finally{A(!1)}},ee=async n=>{var Ye;const V=(Ye=n.target.files)==null?void 0:Ye[0];if(V){if(!["image/png","image/jpeg","image/jpg"].includes(V.type)){o({title:"Formato no válido",description:"Solo se permiten archivos PNG o JPEG",variant:"destructive"});return}if(V.size>500*1024){o({title:"Archivo muy grande",description:"El archivo debe ser menor a 500KB",variant:"destructive"});return}try{D(!0);const xe=`logo-${Date.now()}.${V.name.split(".").pop()}`,{error:Ze}=await N.storage.from("certificate-logos").upload(xe,V,{upsert:!0});if(Ze)throw Ze;const{data:ps}=N.storage.from("certificate-logos").getPublicUrl(xe);$(ps.publicUrl),o({title:"Logo cargado",description:"El logo se ha cargado correctamente"})}catch(xe){console.error("Error uploading logo:",xe),o({title:"Error",description:"No se pudo cargar el logo",variant:"destructive"})}finally{D(!1)}}},de=()=>{$(null)},q=async()=>{try{P(!0);const n={header_text:y,subtitle_text:E||null,event_date_location:l||null,footer_text:v||null,logo_url:T,include_name:B,include_lastname:c,include_document_type:F,include_document_number:K,include_category:i,include_email:b,include_phone:se,include_amount:s,include_currency:k,include_registration_date:ie};if(d){const{error:V}=await N.from("certificate_config").update(n).eq("id",d.id);if(V)throw V}else{const{error:V}=await N.from("certificate_config").insert(n);if(V)throw V}o({title:"Configuración guardada",description:"Los cambios se han guardado correctamente"}),oe()}catch(n){console.error("Error saving config:",n),o({title:"Error",description:"No se pudo guardar la configuración",variant:"destructive"})}finally{P(!1)}};return j?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(R,{className:"w-8 h-8 animate-spin text-primary"})}):e.jsxs(G,{children:[e.jsxs(X,{children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(ue,{className:"w-5 h-5"}),"Configuración del Comprobante de Inscripción"]}),e.jsx(Z,{children:"Define qué información se mostrará en el comprobante de inscripción que se enviará por correo electrónico"})]}
11),e.jsxs(H,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{htmlFor:"header",children:"Texto del encabezado"}),e.jsx(U,{id:"header",value:y,onChange:n=>w(n.target.value),placeholder:"COMPROBANTE DE INSCRIPCIÓN",className:"font-medium"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{htmlFor:"subtitle",children:"Subtítulo del evento"}),e.jsx(Be,{id:"subtitle",value:E,onChange:n=>g(n.target.value),placeholder:`XIII Congreso Regional de Seguridad Radiológica
12Nombre del evento`,rows:3}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Usa saltos de línea para separar líneas"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{htmlFor:"dateLocation",children:"Fecha y lugar del evento"}),e.jsx(U,{id:"dateLocation",value:l,onChange:n=>p(n.target.value),placeholder:"18 al 22 de Octubre de 2026 | Medellín, Colombia"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{htmlFor:"footer",children:"Texto del pie de página"}),e.jsx(U,{id:"footer",value:v,onChange:n=>O(n.target.value),placeholder:"Gracias por su participación en nuestro evento"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{children:"Logotipo del evento"}),e.jsx("div",{className:"flex items-start gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(U,{type:"file",accept:"image/png,image/jpeg,image/jpg",onChange:ee,className:"hidden",disabled:L}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:L,asChild:!0,children:e.jsxs("span",{children:[L?e.jsx(R,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx($e,{className:"w-4 h-4 mr-2"}),"Seleccionar archivo"]})})]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:T?"Archivo seleccionado":"Ningún archivo seleccionado"})]}),e.jsx("p",{className:"text-xs text-blue-600 mt-1",children:"Recomendado: PNG o JPEG, máximo 500KB"})]})}),T&&e.jsxs("div",{className:"relative inline-block mt-4 p-4 border rounded-lg bg-muted/30",children:[e.jsx("img",{src:T,alt:"Logo del evento",className:"max-w-[200px] max-h-[100px] object-contain"}),e.jsx(C,{variant:"destructive",size:"icon",className:"absolute -top-2 -right-2 h-6 w-6",onClick:de,children:e.jsx(js,{className:"w-3 h-3"})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(_,{className:"text-base font-semibold",children:"Campos a incluir en el comprobante"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Selecciona qué información del inscrito aparecerá en el comprobante"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(z,{id:"includeName",checked:B,onCheckedChange:n=>t(!!n)}),e.jsx(_,{htmlFor:"includeName",className:"cursor-pointer",children:"Nombre"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(z,{id:"includeLastname",checked:c,onCheckedChange:n=>f(!!n)}),e.jsx(_,{htmlFor:"includeLastname",className:"cursor-pointer",children:"Apellido"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(z,{id:"includeDocumentType",checked:F,onCheckedChange:n=>Q(!!n)}),e.jsx(_,{htmlFor:"includeDocumentType",className:"cursor-pointer",children:"Tipo de documento"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(z,{id:"includeDocumentNumber",checked:K,onCheckedChange:n=>u(!!n)}),e.jsx(_,{htmlFor:"includeDocumentNumber",className:"cursor-pointer",children:"Número de documento"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(z,{id:"includeCategory",checked:i,onCheckedChange:n=>r(!!n)}),e.jsx(_,{htmlFor:"includeCategory",className:"cursor-pointer",children:"Categoría"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(z,{id:"includeEmail",checked:b,onCheckedChange:n=>S(!!n)}),e.jsx(_,{htmlFor:"includeEmail",className:"cursor-pointer",children:"Correo electrónico"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(z,{id:"includePhone",checked:se,onCheckedChange:n=>me(!!n)}),e.jsx(_,{htmlFor:"includePhone",className:"cursor-pointer",children:"Teléfono"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(z,{id:"includeAmount",checked:s,onCheckedChange:n=>m(!!n)}),e.jsx(_,{htmlFor:"includeAmount",className:"cursor-pointer",children:"Monto pagado"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(z,{id:"includeCurrency",checked:k,onCheckedChange:n=>ne(!!n)}),e.jsx(_,{htmlFor:"includeCurrency",className:"cursor-pointer",children:"Moneda"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(z,{id:"includeRegistrationDate",checked:ie,onCheckedChange:n=>le(!!n)}),e.jsx(_,{htmlFor:"includeRegistrationDate",className:"cursor-pointer",children:"Fecha de inscripción"})]})]})]}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs(C,{onClick:q,disabled:h,className:"gap-2",children:[h?e.jsx(R,{className:"w-4 h-4 animate-spin"}):e.jsx(Le,{className:"w-4 h-4"}),"Guardar configuración"]})})]})]})},pe=[{id:"participantes",label:"Gestión de Participantes"},{id:"usuarios",label:"Gestión de Administradores"},{id:"patrocinadores",label:"Gestión de Patrocinadores"},{id:"resumenes",label:"Gestión de Resúmenes"},{id:"trabajos_finales",label:"Revisión de Trabajos"},{id:"jueces",label:"Gestión de Jueces"},{id:"asignaciones",label:"Asignación de Trabajos"},{id:"estadisticas",label:"Estadísticas de Evaluación"},{id:"registraciones",label:"Validar Certificados"},{id:"plantillas",label:"Plantillas de Póster"},{id:"auditoria",label:"Auditoría de Accesos"},{id:"tarifas",label:"Gestión de Tarifas"},{id:"claves_oferta",label:"Claves de Oferta Comercial"},{id:"emails_masivos",label:"Emails Masivos"},{id:"backups",label:"Gestión de Respaldos"},{id:"pagos",label:"Gestión de Pagos"},{id:"codigos_descuento",label:"Códigos de Descuento"},{id:"configuracion",label:"Configuración del Sistema"}],ea=()=>{const{userRole:o}=gs(),{toast:j}
12=ce(),[A,h]=a.useState([]),[P,L]=a.useState(!0),[D,d]=a.useState(!1),[x,y]=a.useState(!1),[w,E]=a.useState(!1),[g,l]=a.useState(null),[p,v]=a.useState(!1),[O,T]=a.useState(!1),[$,B]=a.useState([]),[t,c]=a.useState({email:"",password:"",full_name:"",institution:"",country:"",phone:"",role:"registration_staff",permissions:[]});a.useEffect(()=>{f()},[]);const f=async()=>{try{L(!0);const{data:s,error:m}=await N.from("profiles").select("*").order("created_at",{ascending:!1});if(m)throw m;const{data:k,error:ne}=await N.from("user_roles").select("*");if(ne)throw ne;const{data:ie,error:le}=await N.from("admin_permissions").select("user_id, permission");if(le)throw le;const oe=(s==null?void 0:s.map(ee=>{const de=k==null?void 0:k.find(n=>n.user_id===ee.id),q=(ie==null?void 0:ie.filter(n=>n.user_id===ee.id).map(n=>n.permission))||[];return{...ee,role:(de==null?void 0:de.role)||"participant",permissions:q}}).filter(ee=>ee.role==="super_admin"||ee.role==="admin_association"||ee.role==="registration_staff"))||[];h(oe)}catch(s){console.error("Error fetching users:",s),j({title:"Error",description:"No se pudieron cargar los usuarios",variant:"destructive"})}finally{L(!1)}},F=async()=>{if(!t.email||!t.password||!t.full_name||!t.role){j({title:"Error",description:"Por favor completa todos los campos obligatorios",variant:"destructive"});return}try{v(!0);const s=t.role==="registration_staff"?"create-registration-user":"create-admin-user",{data:m,error:k}=await N.functions.invoke(s,{body:{email:t.email,password:t.password,full_name:t.full_name,institution:t.institution||null,country:t.country||null,phone:t.phone||null,role:t.role,permissions:t.role!=="super_admin"?t.permissions:[]}});if(k)throw new Error("Error de conexión. Verifica tu conexión a internet.");if((m==null?void 0:m.success)===!1)throw new Error((m==null?void 0:m.error)||"Error desconocido al crear el usuario");j({title:"Usuario creado",description:`El usuario ${t.email} ha sido creado exitosamente`}),d(!1),i(),f()}catch(s){console.error("Error creating user:",s),j({title:"Error al crear usuario",description:s.message||"No se pudo crear el usuario",variant:"destructive"})}finally{v(!1)}},Q=async()=>{if(!g)return;const{data:{user:s}}=await N.auth.getUser();if((s==null?void 0:s.id)===g.id){j({title:"Operación no permitida",description:"No puedes eliminarte a ti mismo",variant:"destructive"});return}try{T(!0);const{data:m,error:k}=await N.functions.invoke("delete-admin-user",{body:{admin_user_id:g.id}});if(k)throw new Error("Error de conexión. Verifica tu conexión a internet.");if(!(m!=null&&m.success))throw new Error((m==null?void 0:m.error)||"Error desconocido al eliminar el usuario");j({title:"Usuario eliminado",description:m.message||"El usuario ha sido eliminado del sistema"}),E(!1),l(null),f()}catch(m){console.error("Error deleting user:",m),j({title:"No se pudo eliminar",description:m.message,variant:"destructive"})}finally{T(!1)}},K=async s=>{l(s),B(s.permissions),y(!0)},u=async()=>{if(g)try{if(v(!0),await N.from("admin_permissions").delete().eq("user_id",g.id),$.length>0){const{data:{user:s}}=await N.auth.getUser(),{error:m}=await N.from("admin_permissions").insert($.map(k=>({user_id:g.id,permission:k,granted_by:s==null?void 0:s.id})));if(m)throw m}j({title:"Permisos actualizados",description:`Se asignaron ${$.length} permisos al usuario`}),y(!1),l(null),B([]),f()}catch(s){console.error("Error saving permissions:",s),j({title:"Error",description:"No se pudieron guardar los permisos",variant:"destructive"})}finally{v(!1)}},i=()=>{c({email:"",password:"",full_name:"",institution:"",country:"",phone:"",role:"registration_staff",permissions:[]})},r=s=>{B(m=>m.includes(s)?m.filter(k=>k!==s):[...m,s])},b=s=>{c(m=>({...m,permissions:m.permissions.includes(s)?m.permissions.filter(k=>k!==s):[...m.permissions,s]}))},S=s=>({super_admin:"Superadministrador",admin_association:"Administración",registration_staff:"Staff de Registro"})[s]||s,se=s=>({super_admin:"bg-teal-600 text-white hover:bg-teal-700",admin_association:"bg-orange-500 text-white hover:bg-orange-600",registration_staff:"bg-blue-500 text-white hover:bg-blue-600"})[s]||"bg-gray-500 text-white",me=s=>{try{return je(new Date(s),"dd/MM/yyyy",{locale:Me})}catch{return s}};return e.jsxs(G,{children:[e.jsx(X,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(We,{className:"h-6 w-6 text-primary"}),e.jsxs("div",{children:[e.jsx(J,{children:"Gestión de Usuarios"}),e.jsx(Z,{children:"Administra los usuarios del sistema de registro"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(C,{variant:"outline",onClick:f,disabled:P,children:[e.jsx(cs,{className:`h-4 w-4 mr-2 ${P?"animate-spin":""}`}),"Actualizar"]}),o==="super_admin"&&e.jsxs(C,{onClick:()=>d(!0),children:[e.jsx(ds,{className:"h-4 w-4 mr-2"}),"Crear usuario"]})]})]})}
12),e.jsxs(H,{children:[P?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(R,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsx("div",{className:"rounded-md border",children:e.jsxs(Se,{children:[e.jsx(Ee,{children:e.jsxs(te,{children:[e.jsx(M,{children:"Correo electrónico"}),e.jsx(M,{children:"Rol"}),e.jsx(M,{children:"Estado"}),e.jsx(M,{children:"Permisos"}),e.jsx(M,{children:"Fecha de creación"}),e.jsx(M,{className:"text-right",children:"Acciones"})]})}),e.jsx(ke,{children:A.length===0?e.jsx(te,{children:e.jsx(I,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No hay usuarios del sistema registrados"})}):A.map(s=>e.jsxs(te,{children:[e.jsx(I,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:s.email}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s.full_name})]})}),e.jsx(I,{children:e.jsx(Y,{className:se(s.role),children:S(s.role)})}),e.jsx(I,{children:e.jsx(Y,{className:"bg-green-500 text-white hover:bg-green-600",children:"Activo"})}),e.jsx(I,{children:s.role==="super_admin"?e.jsx("span",{className:"text-sm text-muted-foreground",children:"Todos los permisos"}):e.jsxs("span",{className:"text-sm text-muted-foreground",children:[s.permissions.length," permisos"]})}),e.jsx(I,{children:me(s.created_at)}),e.jsx(I,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[s.role!=="super_admin"&&o==="super_admin"&&e.jsx(C,{variant:"ghost",size:"icon",onClick:()=>K(s),title:"Gestionar permisos",children:e.jsx(os,{className:"h-4 w-4"})}),o==="super_admin"&&e.jsx(C,{variant:"ghost",size:"icon",onClick:()=>{l(s),E(!0)},className:"text-destructive hover:text-destructive",title:"Eliminar usuario",children:e.jsx(we,{className:"h-4 w-4"})})]})})]},s.id))})]})}),e.jsx(Ie,{open:D,onOpenChange:d,children:e.jsxs(Ae,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Re,{children:[e.jsx(Te,{children:"Crear nuevo usuario"}),e.jsx(as,{children:"Ingresa los datos del nuevo usuario del sistema"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{htmlFor:"email",children:"Correo electrónico *"}),e.jsx(U,{id:"email",type:"email",value:t.email,onChange:s=>c({...t,email:s.target.value}),placeholder:"[email protected]"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{htmlFor:"password",children:"Contraseña *"}),e.jsx(As,{id:"password",value:t.password,onChange:s=>c({...t,password:s.target.value}),placeholder:"Mínimo 8 caracteres"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{htmlFor:"full_name",children:"Nombre completo *"}),e.jsx(U,{id:"full_name",value:t.full_name,onChange:s=>c({...t,full_name:s.target.value}),placeholder:"Nombre y apellidos"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{htmlFor:"role",children:"Rol *"}),e.jsxs(ge,{value:t.role,onValueChange:s=>c({...t,role:s}),children:[e.jsx(fe,{children:e.jsx(ve,{placeholder:"Selecciona un rol"})}),e.jsxs(Ne,{children:[e.jsx(W,{value:"super_admin",children:"Superadministrador"}),e.jsx(W,{value:"admin_association",children:"Administración"}),e.jsx(W,{value:"registration_staff",children:"Staff de Registro"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{htmlFor:"institution",children:"Institución"}),e.jsx(U,{id:"institution",value:t.institution,onChange:s=>c({...t,institution:s.target.value}),placeholder:"Nombre de la institución"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{htmlFor:"country",children:"País"}),e.jsx(U,{id:"country",value:t.country,onChange:s=>c({...t,country:s.target.value}),placeholder:"País"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{htmlFor:"phone",children:"Teléfono"}),e.jsx(U,{id:"phone",value:t.phone,onChange:s=>c({...t,phone:s.target.value}),placeholder:"+57 300 000 0000"})]}),t.role!=="super_admin"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(_,{children:"Permisos del módulo"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>c(s=>({...s,permissions:pe.map(m=>m.id)})),children:"Seleccionar todos"}),e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>c(s=>({...s,permissions:[]})),children:"Limpiar"})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-48 overflow-y-auto border rounded-md p-3",children:pe.map(s=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(z,{id:`form-${s.id}
12`,checked:t.permissions.includes(s.id),onCheckedChange:()=>b(s.id)}),e.jsx(_,{htmlFor:`form-${s.id}`,className:"text-sm font-normal cursor-pointer",children:s.label})]},s.id))})]})]}),e.jsxs(rs,{children:[e.jsx(C,{variant:"outline",onClick:()=>d(!1),children:"Cancelar"}),e.jsxs(C,{onClick:F,disabled:p,children:[p&&e.jsx(R,{className:"h-4 w-4 mr-2 animate-spin"}),"Crear usuario"]})]})]})}),e.jsx(Ie,{open:x,onOpenChange:y,children:e.jsxs(Ae,{className:"max-w-lg",children:[e.jsxs(Re,{children:[e.jsx(Te,{children:"Gestionar permisos"}),e.jsxs(as,{children:[g==null?void 0:g.email," - ",g==null?void 0:g.full_name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(_,{children:"Módulos disponibles"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>B(pe.map(s=>s.id)),children:"Seleccionar todos"}),e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>B([]),children:"Limpiar"})]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 max-h-64 overflow-y-auto border rounded-md p-3",children:pe.map(s=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(z,{id:`perm-${s.id}`,checked:$.includes(s.id),onCheckedChange:()=>r(s.id)}),e.jsx(_,{htmlFor:`perm-${s.id}`,className:"text-sm font-normal cursor-pointer",children:s.label})]},s.id))})]}),e.jsxs(rs,{children:[e.jsx(C,{variant:"outline",onClick:()=>y(!1),children:"Cancelar"}),e.jsxs(C,{onClick:u,disabled:p,children:[p&&e.jsx(R,{className:"h-4 w-4 mr-2 animate-spin"}),"Guardar permisos"]})]})]})}),e.jsx(Ue,{open:w,onOpenChange:E,children:e.jsxs(Ge,{children:[e.jsxs(He,{children:[e.jsx(Ve,{children:"¿Eliminar usuario?"}),e.jsxs(Qe,{children:["Esta acción eliminará permanentemente al usuario ",e.jsx("strong",{children:g==null?void 0:g.email})," del sistema. Esta acción no se puede deshacer."]})]}),e.jsxs(Ke,{children:[e.jsx(Xe,{children:"Cancelar"}),e.jsxs(Je,{onClick:Q,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:O,children:[O&&e.jsx(R,{className:"h-4 w-4 mr-2 animate-spin"}),"Eliminar"]})]})]})})]})]})},sa=()=>{const{toast:o}=ce(),[j,A]=a.useState([]),[h,P]=a.useState([]),[L,D]=a.useState(!0),[d,x]=a.useState(!1),[y,w]=a.useState("Recordatorio: Complete su inscripción al XIII Congreso Regional IRPA 2026"),[E,g]=a.useState(`Le recordamos que su pre-inscripción al XIII Congreso Regional de Seguridad Radiológica y Nuclear está pendiente de pago.
13
14Para completar su registro y asegurar su participación en este importante evento científico, le invitamos a realizar el pago correspondiente a través de su portal de participante.
15
16Fechas importantes:
17• Congreso: 18 - 22 de Octubre de 2026
18• Sede: Centro de Eventos Fórum UPB, Medellín, Colombia
19
20Si tiene alguna consulta, escríbanos al correo [email protected].
21
22¡Esperamos contar con su participación!`),[l,p]=a.useState(null);a.useEffect(()=>{v()},[]);const v=async()=>{try{D(!0);const{data:t,error:c}=await N.from("registrations").select("id, primary_email, first_name, first_surname, full_name, category, created_at").eq("status","pre_registrado").eq("payment_status","pending").order("created_at",{ascending:!1});if(c)throw c;A(t||[])}catch(t){console.error("Error fetching participants:",t),o({title:"Error",description:"No se pudieron cargar los participantes",variant:"destructive"})}finally{D(!1)}},O=t=>{P(t?j.map(c=>c.id):[])},T=(t,c)=>{P(c?[...h,t]:h.filter(f=>f!==t))},$=async()=>{if(!y.trim()||!E.trim()){o({title:"Campos requeridos",description:"Por favor complete el asunto y el mensaje",variant:"destructive"});return}const t=h.length>0?h.length:j.length;if(t===0){o({title:"Sin destinatarios",description:"No hay participantes pre-inscritos sin pago",variant:"destructive"});return}if(window.confirm(`¿Está seguro de enviar este email a ${t} participante(s)?
23
24Esta acción no se puede deshacer.`))try{x(!0),p(null);const f=await N.functions.invoke("send-mass-email-preregistered",{body:{subject:y,message:E,recipientIds:h.length>0?h:void 0}});if(f.error)throw f.error;const F=f.data;p({sent:F.sent||0,failed:F.failed||0,total:F.total||t}),o({title:"Envío completado",description:`Se enviaron ${F.sent} de ${F.total} emails`}),v(),P([])}catch(f){console.error("Error sending emails:",f),o({title:"Error",description:f.message||"No se pudieron enviar los emails",variant:"destructive"})}finally{x(!1)}},B=t=>({profesional_tecnico:"Profesional/Técnico",estudiante_pregrado:"Estudiante"})[t]||t;return e.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[e.jsxs(G,{children:[e.jsxs(X,{children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"h-5 w-5"}),"Componer Email"]}),e.jsx(Z,{children:"Personaliza el mensaje que se enviará a los participantes"})]}
24),e.jsxs(H,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Asunto"}),e.jsx(U,{value:y,onChange:t=>w(t.target.value),placeholder:"Asunto del email"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Mensaje"}),e.jsx(Be,{value:E,onChange:t=>g(t.target.value),rows:12,placeholder:"Escriba el mensaje...",className:"resize-none"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Puede usar ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{nombre}"})," para personalizar con el nombre del participante"]})]}),e.jsxs(be,{children:[e.jsx(ms,{className:"h-4 w-4"}),e.jsx(ye,{children:"Información"}),e.jsx(_e,{children:h.length>0?`Se enviará a ${h.length} participante(s) seleccionado(s)`:`Se enviará a todos los ${j.length} pre-inscritos sin pago`})]}),l&&e.jsxs(be,{variant:l.failed>0?"destructive":"default",children:[l.failed>0?e.jsx(ze,{className:"h-4 w-4"}):e.jsx(he,{className:"h-4 w-4"}),e.jsx(ye,{children:"Resultado del envío"}),e.jsxs(_e,{children:["Enviados: ",l.sent," / ",l.total,l.failed>0&&` • Fallidos: ${l.failed}`]})]}),e.jsx(C,{onClick:$,disabled:d||j.length===0,className:"w-full",size:"lg",children:d?e.jsxs(e.Fragment,{children:[e.jsx(R,{className:"h-4 w-4 mr-2 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"h-4 w-4 mr-2"}),"Enviar Emails"]})})]})]}),e.jsxs(G,{children:[e.jsxs(X,{children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(We,{className:"h-5 w-5"}),"Destinatarios",e.jsxs(Y,{variant:"secondary",className:"ml-auto",children:[j.length," pre-inscritos"]})]}),e.jsx(Z,{children:"Participantes pre-inscritos con pago pendiente"})]}),e.jsx(H,{children:L?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(R,{className:"h-8 w-8 animate-spin text-primary"})}):j.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(he,{className:"h-12 w-12 mx-auto mb-4 text-green-500"}),e.jsx("p",{className:"font-medium",children:"¡Excelente!"}),e.jsx("p",{className:"text-sm",children:"No hay participantes pre-inscritos con pago pendiente"})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(z,{id:"select-all",checked:h.length===j.length&&j.length>0,onCheckedChange:O}),e.jsxs("label",{htmlFor:"select-all",className:"text-sm font-medium cursor-pointer",children:["Seleccionar todos (",j.length,")"]})]}),e.jsx("div",{className:"max-h-[400px] overflow-y-auto rounded-md border",children:e.jsxs(Se,{children:[e.jsx(Ee,{children:e.jsxs(te,{children:[e.jsx(M,{className:"w-12"}),e.jsx(M,{children:"Nombre"}),e.jsx(M,{children:"Email"}),e.jsx(M,{children:"Categoría"})]})}),e.jsx(ke,{children:j.map(t=>e.jsxs(te,{children:[e.jsx(I,{children:e.jsx(z,{checked:h.includes(t.id),onCheckedChange:c=>T(t.id,!!c)})}),e.jsx(I,{className:"font-medium",children:t.first_name&&t.first_surname?`${t.first_name} ${t.first_surname}`:t.full_name||"-"}),e.jsx(I,{className:"text-sm text-muted-foreground",children:t.primary_email}),e.jsx(I,{children:e.jsx(Y,{variant:"outline",className:"text-xs",children:B(t.category)})})]},t.id))})]})})]})})]})]})},aa=()=>{const{toast:o}=ce(),[j,A]=a.useState([]),[h,P]=a.useState([]),[L,D]=a.useState(!0),[d,x]=a.useState(!1),[y,w]=a.useState("Recordatorio: Cargue su trabajo final - XIII Congreso Regional IRPA 2026"),[E,g]=a.useState(`Le recordamos que su resumen "{titulo_resumen}" fue aprobado en modalidad {modalidad} para presentarse en el XIII Congreso Regional de Seguridad Radiológica y Nuclear.
25
26Aún no hemos recibido la carga de su trabajo final en el portal de participantes. La fecha límite para esta entrega es el {fecha_limite}.
27
28Para Pósters: tamaño 56 x 122 cm. Por favor revise las plantillas y guías oficiales disponibles en su portal.
29
30Ingrese a su portal de participante y suba el archivo final lo antes posible para asegurar su participación en el programa científico.
31
32Si tiene alguna consulta, escríbanos al correo [email protected].
33
34¡Gracias por su valioso aporte al Congreso!`),[l,p]=a.useState(null),[v,O]=a.useState(!1),[T,$]=a.useState(!1),[B,t]=a.useState([]),[c,f]=a.useState("[email protected]"),[F,Q]=a.useState(!1),K=v?B:j,u=T?new Set(K.map(s=>s.contact_email.trim().toLowerCase())).size:K.length,i=async()=>{if(c.trim())try{Q(!0);const s=await N.functions.invoke("send-final-work-reminder",{body:{subject:y,message:E,includeSubmitted:v,groupByRecipient:T,testEmail:c}});if(s.error)throw s.error;o({title:"Prueba enviada",description:`Se envió una prueba a ${c}`})}catch(s){o({title:"Error",description:s.message||"No se pudo enviar la prueba",variant:"destructive"})}finally{Q(!1)}};a.useEffect(()=>{r()},[]);const r=async()=>{try{D(!0);const{data:s,error:m}=await N.from("abstracts").select("id, title, status, contact_email, user_id, authors, updated_at").eq("is_latest_version",!0).in("status",["approved_oral","approved_poster"]).order("updated_at",{ascending:!1});if(m)throw m;const k=(s||[]).map(q=>q.id);let ne=new Set;if(k.length>0){const{data:q}=await N.from("final_submissions").select("abstract_id").in("abstract_id",k);ne=new Set((q||[]).map(n=>n.abstract_id))}const ie=[...new Set((s||[]).map(q=>q.user_id))],le=new Map;if(ie.length>0){const{data:q}=await N.from("registrations").select("user_id, first_name, first_surname, full_name").in("user_id",ie);(q||[]).forEach(n=>{const V=n.first_name&&n.first_surname?`${n.first_name} ${n.first_surname}`:n.full_name||"";le.set(n.user_id,V)})}const oe=q=>{var n,V;return{abstract_id:q.id,title:q.title,status:q.status,contact_email:q.contact_email,user_id:q.user_id,author_name:le.get(q.user_id)||((V=(n=q.authors)==null?void 0:n.split(",")[0])==null?void 0:V.trim())||"-",updated_at:q.updated_at}},ee=(s||[]).map(oe),de=(s||[]).filter(q=>!ne.has(q.id)).map(oe);t(ee),A(de)}catch(s){console.error("Error fetching pending:",s),o({title:"Error",description:"No se pudieron cargar los resúmenes pendientes",variant:"destructive"})}finally{D(!1)}},b=s=>{P(s?j.map(m=>m.abstract_id):[])},S=(s,m)=>{P(m?[...h,s]:h.filter(k=>k!==s))},se=async()=>{if(!y.trim()||!E.trim()){o({title:"Campos requeridos",description:"Complete el asunto y el mensaje",variant:"destructive"});return}const s=h.length>0?h.length:u;if(s===0){o({title:"Sin destinatarios",description:"No hay resúmenes aprobados sin trabajo final",variant:"destructive"});return}if(window.confirm(`¿Enviar recordatorio a ${s} autor(es)?
35
36Esta acción no se puede deshacer.`))try{x(!0),p(null);const m=await N.functions.invoke("send-final-work-reminder",{body:{subject:y,message:E,recipientAbstractIds:h.length>0?h:void 0,includeSubmitted:v,groupByRecipient:T}});if(m.error)throw m.error;const k=m.data;if((k==null?void 0:k.success)===!1)throw new Error(k.error||"Error desconocido");p({sent:k.sent||0,failed:k.failed||0,total:k.total||s}),o({title:"Envío completado",description:`Se enviaron ${k.sent} de ${k.total} recordatorios`}),P([]),r()}catch(m){console.error("Error sending reminders:",m),o({title:"Error",description:m.message||"No se pudieron enviar los recordatorios",variant:"destructive"})}finally{x(!1)}},me=s=>s==="approved_oral"?e.jsx(Y,{className:"bg-blue-600",children:"Oral"}):s==="approved_poster"?e.jsx(Y,{className:"bg-emerald-600",children:"Póster"}):e.jsx(Y,{variant:"outline",children:s});return e.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[e.jsxs(G,{children:[e.jsxs(X,{children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(Ce,{className:"h-5 w-5"})," Componer Recordatorio"]}),e.jsx(Z,{children:"Mensaje para autores con resumen aprobado sin trabajo final cargado"})]}
36),e.jsxs(H,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Asunto"}),e.jsx(U,{value:y,onChange:s=>w(s.target.value),placeholder:"Asunto del email"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Mensaje"}),e.jsx(Be,{value:E,onChange:s=>g(s.target.value),rows:14,className:"resize-none"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Variables: ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{nombre}"})," ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{titulo_resumen}"})," ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{modalidad}"})," ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{fecha_limite}"})]})]}),e.jsxs("div",{className:"space-y-2 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{id:"include-submitted",checked:v,onCheckedChange:s=>O(!!s)}),e.jsx("label",{htmlFor:"include-submitted",className:"text-sm cursor-pointer",children:"Incluir a quienes ya cargaron su trabajo final"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{id:"group-recipient",checked:T,onCheckedChange:s=>$(!!s)}),e.jsx("label",{htmlFor:"group-recipient",className:"text-sm cursor-pointer",children:"Un solo correo por persona (sin título del resumen)"})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"block text-sm font-medium mb-2",children:"Correo de prueba"}),e.jsx(U,{value:c,onChange:s=>f(s.target.value),placeholder:"[email protected]"})]}),e.jsx(C,{variant:"outline",onClick:i,disabled:F,children:F?e.jsx(R,{className:"h-4 w-4 animate-spin"}):"Enviar prueba"})]}),e.jsxs(be,{children:[e.jsx(ms,{className:"h-4 w-4"}),e.jsx(ye,{children:"Información"}),e.jsx(_e,{children:h.length>0?`Se enviará a ${h.length} resumen(es) seleccionado(s)`:`Se enviará a ${u} destinatario(s)`})]}),l&&e.jsxs(be,{variant:l.failed>0?"destructive":"default",children:[l.failed>0?e.jsx(ze,{className:"h-4 w-4"}):e.jsx(he,{className:"h-4 w-4"}),e.jsx(ye,{children:"Resultado del envío"}),e.jsxs(_e,{children:["Enviados: ",l.sent," / ",l.total,l.failed>0&&` • Fallidos: ${l.failed}`]})]}),e.jsx(C,{onClick:se,disabled:d||u===0,className:"w-full",size:"lg",children:d?e.jsxs(e.Fragment,{children:[e.jsx(R,{className:"h-4 w-4 mr-2 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"h-4 w-4 mr-2"}),"Enviar Recordatorios"]})})]})]}),e.jsxs(G,{children:[e.jsxs(X,{children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(ue,{className:"h-5 w-5"})," Resúmenes pendientes",e.jsxs(Y,{variant:"secondary",className:"ml-auto",children:[j.length," pendientes"]})]}),e.jsx(Z,{children:"Aprobados (Oral/Póster) sin trabajo final cargado"})]}),e.jsx(H,{children:L?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(R,{className:"h-8 w-8 animate-spin text-primary"})}):j.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(he,{className:"h-12 w-12 mx-auto mb-4 text-green-500"}),e.jsx("p",{className:"font-medium",children:"¡Excelente!"}),e.jsx("p",{className:"text-sm",children:"Todos los autores aprobados ya cargaron su trabajo final"})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(z,{id:"select-all-fw",checked:h.length===j.length&&j.length>0,onCheckedChange:s=>b(!!s)}),e.jsxs("label",{htmlFor:"select-all-fw",className:"text-sm font-medium cursor-pointer",children:["Seleccionar todos (",j.length,")"]})]}),e.jsx("div",{className:"max-h-[400px] overflow-y-auto rounded-md border",children:e.jsxs(Se,{children:[e.jsx(Ee,{children:e.jsxs(te,{children:[e.jsx(M,{className:"w-12"}),e.jsx(M,{children:"Título / Autor"}),e.jsx(M,{children:"Email"}),e.jsx(M,{children:"Modalidad"})]})}),e.jsx(ke,{children:j.map(s=>e.jsxs(te,{children:[e.jsx(I,{children:e.jsx(z,{checked:h.includes(s.abstract_id),onCheckedChange:m=>S(s.abstract_id,!!m)})}),e.jsxs(I,{children:[e.jsx("div",{className:"font-medium text-sm line-clamp-2",children:s.title}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:s.author_name})]}),e.jsx(I,{className:"text-xs text-muted-foreground",children:s.contact_email}),e.jsx(I,{children:me(s.status)})]},s.abstract_id))})]})})]})})]})]})},ra=()=>{const{toast:o}
36=ce(),j=fs(),[A,h]=a.useState(!1),[P,L]=a.useState(""),[D,d]=a.useState(""),{data:x,isLoading:y}=Ms({queryKey:["oferta-access-codes"],queryFn:async()=>{const{data:l,error:p}=await N.from("oferta_access_codes").select("*").order("created_at",{ascending:!1});if(p)throw p;return l}}),w=Pe({mutationFn:async()=>{const{error:l}=await N.from("oferta_access_codes").insert({code:P.toUpperCase(),description:D||null});if(l)throw l},onSuccess:()=>{j.invalidateQueries({queryKey:["oferta-access-codes"]}),o({title:"Código creado exitosamente"}),h(!1),L(""),d("")},onError:l=>{o({title:"Error al crear código",description:l.message,variant:"destructive"})}}),E=Pe({mutationFn:async({id:l,is_active:p})=>{const{error:v}=await N.from("oferta_access_codes").update({is_active:p}).eq("id",l);if(v)throw v},onSuccess:()=>{j.invalidateQueries({queryKey:["oferta-access-codes"]}),o({title:"Estado actualizado"})},onError:l=>{o({title:"Error",description:l.message,variant:"destructive"})}}),g=Pe({mutationFn:async l=>{const{error:p}=await N.from("oferta_access_codes").delete().eq("id",l);if(p)throw p},onSuccess:()=>{j.invalidateQueries({queryKey:["oferta-access-codes"]}),o({title:"Código eliminado"})},onError:l=>{o({title:"Error al eliminar",description:l.message,variant:"destructive"})}});return e.jsxs(G,{children:[e.jsxs(X,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(us,{className:"h-6 w-6 text-primary"}),e.jsx(J,{children:"Claves de Acceso - Oferta Comercial"})]}),e.jsxs(Ie,{open:A,onOpenChange:h,children:[e.jsx(Rs,{asChild:!0,children:e.jsxs(C,{children:[e.jsx(ds,{className:"mr-2 h-4 w-4"}),"Nueva Clave"]})}),e.jsxs(Ae,{children:[e.jsx(Re,{children:e.jsx(Te,{children:"Crear Nueva Clave de Acceso"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{htmlFor:"code",children:"Código"}),e.jsx(U,{id:"code",value:P,onChange:l=>L(l.target.value),placeholder:"Ej: SPONSOR2026",className:"uppercase"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(_,{htmlFor:"description",children:"Descripción (opcional)"}),e.jsx(U,{id:"description",value:D,onChange:l=>d(l.target.value),placeholder:"Ej: Código para patrocinadores"})]}),e.jsxs(C,{onClick:()=>w.mutate(),disabled:!P||w.isPending,className:"w-full",children:[w.isPending?e.jsx(R,{className:"mr-2 h-4 w-4 animate-spin"}):null,"Crear Código"]})]})]})]})]}),e.jsx(H,{children:y?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(R,{className:"h-8 w-8 animate-spin text-primary"})}):x!=null&&x.length?e.jsx("div",{className:"space-y-4",children:x.map(l=>e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("code",{className:"text-lg font-mono font-bold text-primary",children:l.code}),e.jsx(Y,{variant:l.is_active?"default":"secondary",children:l.is_active?"Activo":"Inactivo"})]}),l.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:l.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Creado: ",new Date(l.created_at).toLocaleDateString("es-CO")]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qs,{checked:l.is_active,onCheckedChange:p=>E.mutate({id:l.id,is_active:p})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:l.is_active?"Activo":"Inactivo"})]}),e.jsxs(Ue,{children:[e.jsx(Ts,{asChild:!0,children:e.jsx(C,{variant:"ghost",size:"icon",children:e.jsx(we,{className:"h-4 w-4 text-destructive"})})}),e.jsxs(Ge,{children:[e.jsxs(He,{children:[e.jsx(Ve,{children:"¿Eliminar código?"}),e.jsxs(Qe,{children:['Esta acción no se puede deshacer. El código "',l.code,'" será eliminado permanentemente.']})]}),e.jsxs(Ke,{children:[e.jsx(Xe,{children:"Cancelar"}),e.jsx(Je,{onClick:()=>g.mutate(l.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Eliminar"})]})]})]})]})]},l.id))}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No hay claves de acceso configuradas"})})]})},ta=()=>{var c,f,F,Q,K;const{toast:o}
36=ce(),[j,A]=a.useState(!1),[h,P]=a.useState(null),[L,D]=a.useState(!1),[d,x]=a.useState(!1),[y,w]=a.useState([]),[E,g]=a.useState(!1),[l,p]=a.useState(null),v=async()=>{var u;A(!0);try{const{data:i,error:r}=await N.functions.invoke("export-database-backup",{body:{}});if(r)throw r;P(i),o({title:"Respaldo completado",description:`Se envió el respaldo a ${((u=i.summary)==null?void 0:u.sentTo)||"el email configurado"}`})}catch(i){console.error("Error running backup:",i),o({title:"Error",description:i.message||"No se pudo generar el respaldo",variant:"destructive"})}finally{A(!1)}},O=async()=>{D(!0),w([]),p(null);try{const{data:u,error:i}=await N.functions.invoke("cleanup-orphan-users",{body:{action:"scan"}});if(i)throw i;if(!u.success)throw new Error(u.error);w(u.orphans.map(r=>({...r,selected:!0}))),o({title:"Escaneo completado",description:`Se encontraron ${u.orphan_count} usuarios huérfanos`})}catch(u){console.error("Error scanning orphans:",u),o({title:"Error",description:u.message||"No se pudo escanear usuarios huérfanos",variant:"destructive"})}finally{D(!1)}},T=async()=>{g(!1),x(!0);try{const u=y.filter(b=>b.selected).map(b=>b.id),{data:i,error:r}=await N.functions.invoke("cleanup-orphan-users",{body:{action:"cleanup",user_ids:u}});if(r)throw r;if(!i.success)throw new Error(i.error);p(i),w(b=>b.filter(S=>!u.includes(S.id))),o({title:"Limpieza completada",description:`Se eliminaron ${i.deleted_count} usuarios huérfanos`})}catch(u){console.error("Error cleaning up orphans:",u),o({title:"Error",description:u.message||"No se pudo limpiar usuarios huérfanos",variant:"destructive"})}finally{x(!1)}},$=u=>{w(i=>i.map(r=>r.id===u?{...r,selected:!r.selected}:r))},B=u=>{w(i=>i.map(r=>({...r,selected:u})))},t=y.filter(u=>u.selected).length;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs(G,{children:[e.jsxs(X,{children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"h-5 w-5"}),"Respaldo Automático"]}),e.jsx(Z,{children:"Configuración del respaldo programado"})]}
36),e.jsxs(H,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Estado"}),e.jsxs(Y,{variant:"default",className:"bg-green-500",children:[e.jsx(De,{className:"h-3 w-3 mr-1"}),"Activo"]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Hora de ejecución"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"2:00 AM (Colombia)"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Frecuencia"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Diario"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Destino"}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(qe,{className:"h-3 w-3"}),"Email"]})]})]})]}),e.jsxs(G,{children:[e.jsxs(X,{children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx($s,{className:"h-5 w-5"}),"Respaldo Manual"]}),e.jsx(Z,{children:"Genera un respaldo inmediato bajo demanda"})]}
36),e.jsxs(H,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Ejecuta un respaldo completo de todas las tablas de la base de datos y envíalo por email inmediatamente."}),e.jsx(C,{onClick:v,disabled:j,className:"w-full",children:j?e.jsxs(e.Fragment,{children:[e.jsx(R,{className:"h-4 w-4 mr-2 animate-spin"}),"Generando respaldo..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hs,{className:"h-4 w-4 mr-2"}),"Ejecutar Respaldo Ahora"]})})]})]})]}),h&&e.jsxs(G,{children:[e.jsx(X,{children:e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-5 w-5 text-green-500"}),"Último Respaldo Ejecutado"]})}),e.jsx(H,{children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-primary",children:((c=h.summary)==null?void 0:c.tables)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Tablas respaldadas"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-primary",children:((F=(f=h.summary)==null?void 0:f.totalRecords)==null?void 0:F.toLocaleString())||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Registros totales"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-center",children:[e.jsxs("div",{className:"text-sm font-medium flex items-center justify-center gap-1",children:[e.jsx(qe,{className:"h-4 w-4"}),"Enviado a"]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 break-all",children:((Q=h.summary)==null?void 0:Q.sentTo)||"N/A"})]})]})})]}),e.jsxs(G,{children:[e.jsxs(X,{children:[e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(zs,{className:"h-5 w-5 text-orange-500"}),"Limpieza de Usuarios Huérfanos"]}),e.jsx(Z,{children:"Detecta y elimina usuarios en autenticación sin perfil asociado"})]}
36),e.jsxs(H,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-800",children:[e.jsx(Bs,{className:"h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-sm text-amber-700 dark:text-amber-300",children:"Los usuarios huérfanos son cuentas de autenticación que no tienen perfil en la base de datos. Esto puede ocurrir cuando un registro falla a mitad del proceso."})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(C,{onClick:O,disabled:L||d,variant:"outline",children:L?e.jsxs(e.Fragment,{children:[e.jsx(R,{className:"h-4 w-4 mr-2 animate-spin"}),"Escaneando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(xs,{className:"h-4 w-4 mr-2"}),"Escanear Huérfanos"]})}),y.length>0&&e.jsx(C,{onClick:()=>g(!0),disabled:d||t===0,variant:"destructive",children:d?e.jsxs(e.Fragment,{children:[e.jsx(R,{className:"h-4 w-4 mr-2 animate-spin"}),"Eliminando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(we,{className:"h-4 w-4 mr-2"}),"Eliminar Seleccionados (",t,")"]})})]}),y.length>0&&e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-muted/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"p-3 text-left w-10",children:e.jsx(z,{checked:y.every(u=>u.selected),onCheckedChange:u=>B(!!u)})}),e.jsx("th",{className:"p-3 text-left text-sm font-medium",children:"Email"}),e.jsx("th",{className:"p-3 text-left text-sm font-medium",children:"Fecha de Creación"})]})}),e.jsx("tbody",{children:y.map(u=>e.jsxs("tr",{className:"border-t",children:[e.jsx("td",{className:"p-3",children:e.jsx(z,{checked:u.selected,onCheckedChange:()=>$(u.id)})}),e.jsx("td",{className:"p-3 text-sm",children:u.email}),e.jsx("td",{className:"p-3 text-sm text-muted-foreground",children:new Date(u.created_at).toLocaleDateString("es-CO",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})})]},u.id))})]})}),l&&e.jsxs("div",{className:"p-4 bg-green-50 dark:bg-green-950/20 rounded-lg border border-green-200 dark:border-green-800",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(De,{className:"h-5 w-5 text-green-600"}),e.jsx("span",{className:"font-medium text-green-700 dark:text-green-300",children:"Limpieza completada"})]}),e.jsxs("p",{className:"text-sm text-green-600 dark:text-green-400",children:["Se eliminaron ",l.deleted_count," usuarios huérfanos."]}),((K=l.errors)==null?void 0:K.length)>0&&e.jsxs("p",{className:"text-sm text-red-600 mt-2",children:["Errores: ",l.errors.join(", ")]})]})]})]}),e.jsxs(G,{className:"bg-blue-50 dark:bg-blue-950/20 border-blue-200 dark:border-blue-800",children:[e.jsx(X,{children:e.jsxs(J,{className:"flex items-center gap-2 text-blue-700 dark:text-blue-300",children:[e.jsx(Ns,{className:"h-5 w-5"}),"Información del Sistema de Respaldos"]})}
36),e.jsxs(H,{className:"text-sm text-blue-600 dark:text-blue-400 space-y-2",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Tablas incluidas:"})," abstracts, abstract_assignments, abstract_evaluations, access_audit_logs, admin_action_logs, final_submissions, judge_profiles, oferta_access_codes, participant_attachments, profiles, registration_codes, registration_fees, registrations, sponsors, user_roles"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Formato:"})," El respaldo se envía como archivo JSON adjunto al email, conteniendo todos los datos de las tablas con marca de tiempo."]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Seguridad:"})," Guarde los archivos de respaldo en un lugar seguro. Contienen información sensible del sistema."]})]})]}),e.jsx(Ue,{open:E,onOpenChange:g,children:e.jsxs(Ge,{children:[e.jsxs(He,{children:[e.jsx(Ve,{children:"¿Confirmar eliminación?"}),e.jsxs(Qe,{children:["Esta acción eliminará permanentemente ",t," usuario(s) huérfano(s) del sistema de autenticación. Esta acción no se puede deshacer."]})]}),e.jsxs(Ke,{children:[e.jsx(Xe,{children:"Cancelar"}),e.jsxs(Je,{onClick:T,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:["Eliminar ",t," usuario(s)"]})]})]})})]})},ia=()=>{const[o,j]=a.useState([]),[A,h]=a.useState([]),[P,L]=a.useState(!0),[D,d]=a.useState(""),[x,y]=a.useState(""),[w,E]=a.useState("all"),[g,l]=a.useState("all"),[p,v]=a.useState(1),O=50;a.useEffect(()=>{T()},[]),a.useEffect(()=>{$()},[o,D,x,w,g]);const T=async()=>
36{try{L(!0);const{data:i,error:r}=await N.from("access_audit_logs").select("*").order("created_at",{ascending:!1});if(r)throw r;j(i||[])}catch(i){console.error("Error fetching audit logs:",i)}finally{L(!1)}},$=()=>{let i=[...o];D&&(i=i.filter(r=>r.email.toLowerCase().includes(D.toLowerCase()))),x&&(i=i.filter(r=>{var b;return(b=r.ip_address)==null?void 0:b.includes(x)})),w!=="all"&&(i=i.filter(r=>r.event_type===w)),g!=="all"&&(i=i.filter(r=>r.login_source===g)),h(i),v(1)},B=()=>{const i=A.map(S=>({"Fecha/Hora":je(new Date(S.created_at),"dd/MM/yyyy HH:mm:ss",{locale:Me}),Email:S.email,Evento:c(S.event_type),Fuente:f(S.login_source),IP:S.ip_address||"-",Dispositivo:S.device_type||"-",Navegador:S.browser||"-","Sistema Operativo":S.operating_system||"-",País:S.country||"-",Ciudad:S.city||"-",Error:S.error_message||"-"})),r=Fe.json_to_sheet(i),b=Fe.book_new();Fe.book_append_sheet(b,r,"Auditoría de Accesos"),Us(b,`auditoria_accesos_${je(new Date,"yyyyMMdd_HHmmss")}.xlsx`)},t=i=>{const b={login_success:{label:"✓ Login Exitoso",className:"bg-green-500/20 text-green-700 border-green-500/50"},login_failed:{label:"✗ Login Fallido",className:"bg-red-500/20 text-red-700 border-red-500/50"},logout:{label:"← Logout",className:"bg-yellow-500/20 text-yellow-700 border-yellow-500/50"},signup_success:{label:"+ Registro Exitoso",className:"bg-blue-500/20 text-blue-700 border-blue-500/50"},signup_failed:{label:"✗ Registro Fallido",className:"bg-red-500/20 text-red-700 border-red-500/50"},password_reset_requested:{label:"🔑 Reset Password",className:"bg-purple-500/20 text-purple-700 border-purple-500/50"}}[i]||{label:i,className:"bg-gray-500/20 text-gray-700 border-gray-500/50"};return e.jsx(Y,{className:`${b.className} border`,children:b.label})},c=i=>({login_success:"Login Exitoso",login_failed:"Login Fallido",logout:"Logout",signup_success:"Registro Exitoso",signup_failed:"Registro Fallido",password_reset_requested:"Reset Password"})[i]||i,f=i=>({admin_panel:"Panel Admin",evaluadores:"Evaluadores",participantes:"Participantes",inscribirme:"Inscripción"})[i]||i,F=p*O,Q=F-O,K=A.slice(Q,F),u=Math.ceil(A.length/O);return P?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(R,{className:"h-8 w-8 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(G,{children:[e.jsx(X,{children:e.jsxs(J,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-5 w-5"}),"Filtros de Búsqueda"]})}
36),e.jsxs(H,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Buscar por Email"}),e.jsxs("div",{className:"relative",children:[e.jsx(xs,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(U,{placeholder:"[email protected]",value:D,onChange:i=>d(i.target.value),className:"pl-9"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Buscar por IP"}),e.jsx(U,{placeholder:"192.168.1.1",value:x,onChange:i=>y(i.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Tipo de Evento"}),e.jsxs(ge,{value:w,onValueChange:E,children:[e.jsx(fe,{children:e.jsx(ve,{})}),e.jsxs(Ne,{children:[e.jsx(W,{value:"all",children:"Todos"}),e.jsx(W,{value:"login_success",children:"Login Exitoso"}),e.jsx(W,{value:"login_failed",children:"Login Fallido"}),e.jsx(W,{value:"logout",children:"Logout"}),e.jsx(W,{value:"signup_success",children:"Registro Exitoso"}),e.jsx(W,{value:"signup_failed",children:"Registro Fallido"}),e.jsx(W,{value:"password_reset_requested",children:"Reset Password"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Fuente de Login"}),e.jsxs(ge,{value:g,onValueChange:l,children:[e.jsx(fe,{children:e.jsx(ve,{})}),e.jsxs(Ne,{children:[e.jsx(W,{value:"all",children:"Todas"}),e.jsx(W,{value:"admin_panel",children:"Panel Admin"}),e.jsx(W,{value:"evaluadores",children:"Evaluadores"}),e.jsx(W,{value:"participantes",children:"Participantes"}),e.jsx(W,{value:"inscribirme",children:"Inscripción"})]})]})]})]}),e.jsxs("div",{className:"mt-4 flex justify-between items-center",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Mostrando ",A.length," de ",o.length," registros"]}),e.jsxs(C,{onClick:B,variant:"outline",size:"sm",children:[e.jsx(Oe,{className:"h-4 w-4 mr-2"}),"Exportar a Excel"]})]})]})]}),e.jsx(G,{children:e.jsxs(H,{className:"p-0",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Se,{children:[e.jsx(Ee,{children:e.jsxs(te,{children:[e.jsx(M,{children:"Fecha/Hora"}),e.jsx(M,{children:"Email"}),e.jsx(M,{children:"Evento"}),e.jsx(M,{children:"Fuente"}),e.jsx(M,{children:"IP"}),e.jsx(M,{children:"Dispositivo"}),e.jsx(M,{children:"Navegador"}),e.jsx(M,{children:"Sistema"}),e.jsx(M,{children:"Error"})]})}),e.jsx(ke,{children:K.length===0?e.jsx(te,{children:e.jsx(I,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No se encontraron registros de auditoría"})}):K.map(i=>e.jsxs(te,{children:[e.jsx(I,{className:"whitespace-nowrap",children:je(new Date(i.created_at),"dd/MM/yyyy HH:mm:ss",{locale:Me})}),e.jsx(I,{className:"font-mono text-sm",children:i.email}),e.jsx(I,{children:t(i.event_type)}),e.jsx(I,{children:e.jsx(Y,{variant:"outline",children:f(i.login_source)})}),e.jsx(I,{className:"font-mono text-xs",children:i.ip_address||"-"}),e.jsx(I,{children:i.device_type||"-"}),e.jsx(I,{className:"text-sm",children:i.browser||"-"}),e.jsx(I,{children:i.operating_system||"-"}),e.jsx(I,{className:"max-w-xs truncate text-xs text-red-600",children:i.error_message||"-"})]},i.id))})]})}),u>1&&e.jsxs("div",{className:"flex items-center justify-center gap-2 p-4 border-t",children:[e.jsx(C,{variant:"outline",size:"sm",onClick:()=>v(i=>Math.max(1,i-1)),disabled:p===1,children:"Anterior"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Página ",p," de ",u]}),e.jsx(C,{variant:"outline",size:"sm",onClick:()=>v(i=>Math.min(u,i+1)),disabled:p===u,children:"Siguiente"})]})]})})]})},hr=()=>{const o=vs();return e.jsxs("div",{className:"min-h-screen flex flex-col",children:[e.jsx(bs,{}),e.jsx("main",{className:"flex-grow pt-20",children:e.jsxs("div",{className:"container mx-auto px-4 py-8",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsxs(C,{variant:"ghost",onClick:()=>o("/admin?tab=management"),children:[e.jsx(Qs,{className:"w-4 h-4 mr-2"}),"Volver al Panel"]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold",children:"Configuración del Sistema"}),e.jsx("p",{className:"text-muted-foreground",children:"Documentos legales, emails, respaldos, auditoría y configuración general"})]})]}),e.jsxs(_s,{defaultValue:"usuarios",className:"space-y-6",children:[e.jsxs(Hs,{className:"w-full whitespace-nowrap",children:[e.jsxs(Cs,{className:"inline-flex w-auto",children:[e.jsxs(ae,{value:"usuarios",className:"gap-2",children:[e.jsx(We,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Usuarios"})]}),e.jsxs(ae,{value:"terminos",className:"gap-2",children:[e.jsx(ue,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Términos"})]}),e.jsxs(ae,{value:"habeas",className:"gap-2",children:[e.jsx(Ls,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Habeas Data"})]}),e.jsxs(ae,{value:"comprobante",className:"gap-2",children:[e.jsx(Ks,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Comprobante"})]}),e.jsxs(ae,{value:"impresora",className:"gap-2",children:[e.jsx(ls,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Impresora"})]}),e.jsxs(ae,{value:"emails",className:"gap-2",children:[e.jsx(qe,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Emails Masivos"})]}),e.jsxs(ae,{value:"recordatorio-final",className:"gap-2",children:[e.jsx($e,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Recordatorio Trabajo Final"})]}),e.jsxs(ae,{value:"claves",className:"gap-2",children:[e.jsx(us,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Claves Oferta"})]}),e.jsxs(ae,{value:"respaldos",className:"gap-2",children:[e.jsx(hs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Respaldos"})]}),e.jsxs(ae,{value:"auditoria",className:"gap-2",children:[e.jsx(Xs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Auditoría"})]})]}),e.jsx(Vs,{orientation:"horizontal"})]}),e.jsx(re,{value:"usuarios",children:e.jsx(ea,{})}),e.jsx(re,{value:"terminos",children:e.jsx(ts,{documentType:"terms_conditions",title:"Términos y Condiciones",description:"Documento de términos y condiciones que se mostrará a los participantes durante el registro"})}),e.jsx(re,{value:"habeas",children:e.jsx(ts,{documentType:"habeas_data",title:"Política de Habeas Data",description:"Documento de política de tratamiento de datos personales según la ley de protección de datos"})}),e.jsx(re,{value:"comprobante",children:e.jsx(Zs,{})}),e.jsx(re,{value:"impresora",children:e.jsx(Ys,{})}),e.jsx(re,{value:"emails",children:e.jsx(sa,{})}),e.jsx(re,{value:"recordatorio-final",children:e.jsx(aa,{})}),e.jsx(re,{value:"claves",children:e.jsx(ra,{})}),e.jsx(re,{value:"respaldos",children:e.jsx(ta,{})}),e.jsx(re,{value:"auditoria",children:e.jsx(ia,{})})]})]})}),e.jsx(ys,{})]})};export{hr 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.