1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TicketsManager-DHYSWrhx.js","assets/vendor-query-BC-k7Zad.js","assets/vendor-ui-C7VZ-0Gn.js","assets/index-Bj0IC8l5.js","assets/vendor-supabase-Crkn7ML9.js","assets/vendor-form-DfDjfO12.js","assets/vendor-react-Yoj03Zzx.js","assets/index-CKxKtSU2.css","assets/card-B7ABiRT0.js","assets/textarea-DHnK05X_.js","assets/badge-Caa_2Dk8.js","assets/AdminPageHeader-DvIgSSZ3.js","assets/InfoHint-D--PyuVj.js","assets/info-C54TnQgs.js","assets/Admin-Dby0AgBi.js","assets/command-Ol-I9XRY.js","assets/check-check-BMl6pH6m.js","assets/loader-circle-DZrliUq4.js","assets/dialog-hbl8eKTw.js","assets/search-qnNzSRbK.js","assets/tabs-BYYAjT1z.js","assets/dropdown-menu-3MuLYGRm.js","assets/chevron-right-Biw5yBnB.js","assets/circle-C11Drd_9.js","assets/ShortcutTile-CjWqXFbD.js","assets/format-WUgAigUZ.js","assets/chevron-left-B-l3Pobn.js","assets/calendar-CEDME4bB.js","assets/pt-BR-DobfxFmA.js","assets/skeleton-CfGvjdy7.js","assets/BarChart-QNx7Nv0h.js","assets/ellipsis-cqVnhBWn.js","assets/deviceFingerprint-CGErDH3S.js","assets/clock-B4TMdWnC.js","assets/plug-IoOG3oyR.js","assets/calculator-DHQEgteP.js","assets/link-2-D0e1x2E3.js","assets/trophy-c1Aaravx.js","assets/shield-setyIKcc.js","assets/message-square-HLwEpdNi.js","assets/circle-help-Dn9r2nWL.js","assets/credit-card-DQVtzNX0.js","assets/stethoscope-CyVbdKTA.js","assets/file-text-DxlkC96Q.js","assets/gift-Bwl2EX77.js","assets/Admin-C1OZ1Nvv.css","assets/usePagination-xtOGrgRt.js","assets/AdminPagination-VmrVRUoe.js","assets/AppointmentsManager-CIX2D7Ph.js","assets/invokeSignedFn-IsTmxGxK.js","assets/square-pen-DEcO211f.js","assets/circle-x-DF-finoc.js","assets/BESManager-C_YpbUnv.js","assets/table-M_lckr1I.js","assets/uploadGuard-B6LHVWx0.js","assets/BESRequestsPanel-HMZn3_Hc.js","assets/external-link-C-7l538T.js","assets/BESRequestsPanel-DNPMGCG4.css","assets/plus-BOzF8fAo.js","assets/eye-C_eIX9S8.js","assets/CancellationRequestsManager-DAKMGbXE.js","assets/LgpdRequestsManager-DoB1UGCU.js"])))=>i.map(i=>d[i]); 2import{a as r,u as B,j as e,h as vr}from"./vendor-query-BC-k7Zad.js";import{c as Bt,B as g,R as es,I as $,s as z,u as b,h as P,i as A,j as E,k as R,l as f,X as yr,aF as _r,C as It,L as y,f as Nr,ai as Cr,a0 as Pt,aC as At,a2 as Et,b3 as Rt,a3 as Sr}from"./index-Bj0IC8l5.js";import{a as be,p as qt}from"./pgrstSafe-B5MzxWtV.js";import{i as se}from"./invokeSignedFn-IsTmxGxK.js";import{u as wr,s as kr,A as Mr}from"./Admin-Dby0AgBi.js";import{A as Fr}from"./AdminToolbar-DsuyBr4P.js";import{A as Pr}from"./AdminPagination-VmrVRUoe.js";import{A as Ar,a as zt}from"./AdminFlowOverlay-DshYcDg-.js";import{B as T}from"./badge-Caa_2Dk8.js";import{C as W,a as $s,b as Ts,c as X}from"./card-B7ABiRT0.js";import{G as $t}from"./git-branch-KWQA7dhA.js";import{S as Vt}from"./search-qnNzSRbK.js";import{H as Ot}from"./history-DbnukXMx.js";import{C as Qt}from"./chevron-left-B-l3Pobn.js";import{C as Er}from"./chevron-right-Biw5yBnB.js";import{_ as ss}from"./vendor-supabase-Crkn7ML9.js";import{d as Kt}from"./vendor-react-Yoj03Zzx.js";import{T as Fa}from"./textarea-DHnK05X_.js";import{C as Rr}from"./checkbox-Bfz6RaH4.js";import{P as qr}from"./BESRequestsPanel-HMZn3_Hc.js";import{D as zr,b as $r,c as Tr,d as Dr,f as Lr}from"./dialog-hbl8eKTw.js";import{c as $e}from"./tabs-BYYAjT1z.js";import{T as Br}from"./tag-DwUmstdJ.js";import{L as ae}from"./loader-circle-DZrliUq4.js";import{C as Ir}from"./copy-DIoQvOxE.js";import{E as Vr}from"./external-link-C-7l538T.js";import{C as Or}from"./circle-x-DF-finoc.js";import"./vendor-ui-C7VZ-0Gn.js";import"./vendor-form-DfDjfO12.js";import"./command-Ol-I9XRY.js";import"./check-check-BMl6pH6m.js";import"./dropdown-menu-3MuLYGRm.js";import"./circle-C11Drd_9.js";import"./ShortcutTile-CjWqXFbD.js";import"./format-WUgAigUZ.js";import"./calendar-CEDME4bB.js";import"./pt-BR-DobfxFmA.js";import"./skeleton-CfGvjdy7.js";import"./BarChart-QNx7Nv0h.js";import"./ellipsis-cqVnhBWn.js";import"./deviceFingerprint-CGErDH3S.js";import"./clock-B4TMdWnC.js";import"./plug-IoOG3oyR.js";import"./calculator-DHQEgteP.js";import"./link-2-D0e1x2E3.js";import"./trophy-c1Aaravx.js";import"./shield-setyIKcc.js";import"./message-square-HLwEpdNi.js";import"./circle-help-Dn9r2nWL.js";import"./credit-card-DQVtzNX0.js";import"./stethoscope-CyVbdKTA.js";import"./file-text-DxlkC96Q.js";import"./gift-Bwl2EX77.js";import"./info-C54TnQgs.js";/** 3 * @license lucide-react v0.462.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const Qr=Bt("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/** 8 * @license lucide-react v0.462.0 - ISC 9 * 10 * This source code is licensed under the ISC license. 11 * See the LICENSE file in the root directory of this source tree. 12 */const Kr=Bt("Fingerprint",[["path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4",key:"1nerag"}],["path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88",key:"o46ks0"}],["path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02",key:"ptglia"}],["path",{d:"M2 12a10 10 0 0 1 18-6",key:"ydlgp0"}],["path",{d:"M2 16h.01",key:"1gqxmh"}],["path",{d:"M21.8 16c.2-2 .131-5.354 0-6",key:"drycrb"}
12],["path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2",key:"1tidbn"}],["path",{d:"M8.65 22c.21-.66.45-1.32.57-2",key:"13wd9y"}],["path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2",key:"1fr1j5"}]]),As=20;function Es(a){if(!a)return"â";try{return new Date(a).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return a}}function Pa(a){const i=String(a||"").toLowerCase();return i==="open"?"Em andamento":i==="closed"?"Encerrado":a||"Registrado"}function Aa(a){const i=String(a||"").replace(/\D/g,"");return i.length!==11?a||"â":`${i.slice(0,3)}.***.***-${i.slice(9)}`}function Ze(a,i){if(!i)return!0;const d=i.toLowerCase(),u=d.replace(/\D/g,"");return[a.primary_protocol,a.protocol,a.source,a.subject_name,a.subject_cpf,a.subject_email,a.client_key,a.protocol_origin,a.origin_label,a.reason_label].filter(Boolean).join(" ").toLowerCase().includes(d)?!0:u.length>=3&&String(a.subject_cpf||"").replace(/\D/g,"").includes(u)}function Hr(){const[a,i]=r.useState(""),[d,u]=r.useState(0),p=B({queryKey:["admin-protocol-hierarchy-v2"],staleTime:45e3,queryFn:async()=>{const{data:n,error:F}=await z.rpc("admin_protocol_hierarchy_v2",{p_client_key:null,p_limit:5e3});if(F)throw F;return n||[]}}),j=p.data||[],v=r.useMemo(()=>j.filter(n=>n.node_type==="root"),[j]),c=r.useMemo(()=>j.filter(n=>n.node_type==="historical"),[j]),l=r.useMemo(()=>j.filter(n=>n.node_type==="child"),[j]),N=a.trim().toLowerCase(),U=r.useMemo(()=>{const n=new Map;for(const F of l){if(!F.primary_protocol)continue;const V=n.get(F.primary_protocol)||[];V.push(F),n.set(F.primary_protocol,V)}return n},[l]),I=r.useMemo(()=>N?v.filter(n=>Ze(n,N)?!0:(U.get(n.primary_protocol||"")||[]).some(F=>Ze(F,N))):v,[v,N,U]),G=r.useMemo(()=>c.filter(n=>Ze(n,N)),[c,N]);r.useEffect(()=>u(0),[N]);const J=Math.max(1,Math.ceil(G.length/As));r.useEffect(()=>{d>J-1&&u(Math.max(0,J-1))},[d,J]);const ce=G.slice(d*As,d*As+As),de=v.filter(n=>String(n.root_status||n.status||"").toLowerCase()==="open").length;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(W,{className:"border-border/40",children:[e.jsx($s,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-start md:justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ts,{className:"flex items-center gap-2 text-base",children:[e.jsx($t,{className:"h-4 w-4"})," VÃnculos de atendimento"]}),e.jsx("p",{className:"mt-1 max-w-3xl text-xs text-muted-foreground",children:"Mostra quais solicitações pertencem ao mesmo atendimento e mantém o histórico relacionado agrupado."})]}),e.jsxs(g,{size:"sm",variant:"outline",onClick:()=>p.refetch(),disabled:p.isFetching,children:[e.jsx(es,{className:`mr-1 h-3.5 w-3.5 ${p.isFetching?"animate-spin":""}`})," Atualizar"]})]})}),e.jsxs(X,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:[e.jsx(Rs,{label:"Atendimentos",value:v.length}),e.jsx(Rs,{label:"Abertos",value:de}),e.jsx(Rs,{label:"Solicitações vinculadas",value:l.length}),e.jsx(Rs,{label:"Históricos",value:c.length})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Vt,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx($,{value:a,onChange:n=>i(n.target.value),placeholder:"Buscar protocolo, cliente, CPF ou motivoâ¦",className:"pl-9"})]})]})]}),p.isLoading?e.jsx(W,{children:e.jsx(X,{className:"py-12 text-center text-sm text-muted-foreground",children:"Carregando hierarquiaâ¦"})}):p.isError?e.jsx(W,{children:e.jsx(X,{className:"py-12 text-center text-sm text-destructive",children:"Não foi possÃvel carregar a hierarquia de protocolos."})}):I.length===0&&G.length===0?e.jsx(W,{children:e.jsx(X,{className:"py-12 text-center text-sm text-muted-foreground",children:"Nenhum protocolo encontrado para o filtro informado."})}):e.jsxs(e.Fragment,{children:[I.length>0&&e.jsx("div",{className:"space-y-3",children:I.map(n=>{const F=n.primary_protocol?U.get(n.primary_protocol)||[]:[],V=N&&!Ze(n,N)?F.filter(C=>Ze(C,N)):F,as=String(n.root_status||n.status||"").toLowerCase()==="open";return e.jsx(W,{className:"border-border/40",children:e.jsxs(X,{className:"p-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx($t,{className:"h-4 w-4 text-primary"}),e.jsx("code",{className:"break-all text-xs font-semibold",children:n.protocol}),e.jsx(T,{variant:as?"default":"secondary",children:Pa(n.root_status)})]}),e.jsx("div",{className:"mt-1 text-sm font-medium",children:n.reason_label||"Atendimento iniciado"}),e.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:["CPF ",Aa(n.subject_cpf)," · origem ",n.origin_label||n.protocol_origin||"CS Saúde"]}),e.jsxs("div",{className:"mt-1 text-[11px] text-muted-foreground",children:["InÃcio ",Es(n.root_started_at||n.created_at)," · última atividade ",Es(n.root_last_activity_at||n.updated_at)]})]}),e.jsxs(T,{variant:"outline",className:"shrink-0",children:[F.length," filho(s)"]})]}),V.length>0?e.jsx("div",{className:"mt-4 space-y-2 border-l-2 border-primary/20 pl-4",children:V.map(C=>e.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/10 p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:C.reason_label||C.source||"Solicitação"}),e.jsx("code",{className:"break-all text-xs text-muted-foreground",children:C.protocol||"sem protocolo"})]}),e.jsx(T,{variant:"secondary",children:Pa(C.status)})]}),e.jsxs("div",{className:"mt-1 text-[11px] text-muted-foreground",children:[C.origin_label||C.source||"CS Saúde"," · ",C.subject_name||Aa(C.subject_cpf)," · ",Es(C.created_at)]})]},`${C.source_table}-${C.ref_id}-${C.protocol}`))}):e.jsx("div",{className:"mt-4 rounded-md border border-dashed border-border/50 px-3 py-2 text-xs text-muted-foreground",children:"Nenhuma solicitação filha vinculada a este episódio."})]})},n.primary_protocol||n.ref_id||n.created_at)})}),G.length>0&&e.jsxs(W,{className:"border-border/40",children:[e.jsx($s,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsxs(Ts,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ot,{className:"h-4 w-4"})," Histórico sem vÃnculo"]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Registros históricos que ainda não pertencem a um atendimento agrupado."})]}),e.jsxs(T,{variant:"outline",children:[G.length," registro(s)"]})]})}),e.jsxs(X,{className:"space-y-2",children:[ce.map(n=>e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border/40 p-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:n.reason_label||n.source||"Solicitação"}),e.jsx("code",{className:"break-all text-xs text-muted-foreground",children:n.protocol||"sem protocolo"}),e.jsxs("div",{className:"mt-1 text-[11px] text-muted-foreground",children:[n.origin_label||n.source||"CS Saúde"," · ",n.subject_name||Aa(n.subject_cpf)," · ",Es(n.
12created_at)]})]}),e.jsx(T,{variant:"secondary",className:"shrink-0",children:Pa(n.status)})]},`${n.source_table}-${n.ref_id}-${n.protocol}`)),J>1&&e.jsxs("div",{className:"flex items-center justify-between border-t border-border/40 pt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Página ",d+1," de ",J]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(g,{size:"icon",variant:"outline",className:"h-8 w-8",onClick:()=>u(n=>Math.max(0,n-1)),disabled:d===0,children:e.jsx(Qt,{className:"h-3.5 w-3.5"})}),e.jsx(g,{size:"icon",variant:"outline",className:"h-8 w-8",onClick:()=>u(n=>Math.min(J-1,n+1)),disabled:d>=J-1,children:e.jsx(Er,{className:"h-3.5 w-3.5"})})]})]})]})]})]})]})}function Rs({label:a,value:i}){return e.jsxs("div",{className:"rounded-lg border border-border/40 bg-muted/10 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase tracking-wide text-muted-foreground",children:a}),e.jsx("div",{className:"mt-0.5 text-lg font-semibold tabular-nums",children:i.toLocaleString("pt-BR")})]})}const Ur=r.lazy(()=>ss(()=>import("./TicketsManager-DHYSWrhx.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47]))),Gr=r.lazy(()=>ss(()=>import("./AppointmentsManager-CIX2D7Ph.js"),__vite__mapDeps([48,1,3,2,4,5,6,7,8,9,18,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,49,50,51]))),Wr=r.lazy(()=>ss(()=>import("./BESManager-C_YpbUnv.js"),__vite__mapDeps([52,1,46,47,3,2,4,5,6,7,26,22,9,53,8,11,12,13,10,54,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,49,55,56,57,58,59]))),Xr=r.lazy(()=>ss(()=>import("./CancellationRequestsManager-DAKMGbXE.js"),__vite__mapDeps([60,1,3,2,4,5,6,7,8,18,53,10,9,14,15,16,17,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,11,12,13]))),Zr=r.lazy(()=>ss(()=>import("./LgpdRequestsManager-DoB1UGCU.js"),__vite__mapDeps([61,1,3,2,4,5,6,7,8,18,53,10,9,14,15,16,17,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,11,12,13]))),Ea=[{flow:"tickets",label:"Chamados",helper:"Responder, acompanhar e concluir atendimentos"},{flow:"appointments",label:"Agendamentos",helper:"Consultas, exames e Consulta Fixa BES"},{flow:"bes",label:"CS Bem-Estar",helper:"BenefÃcios, solicitações, autorizações e documentos"},{flow:"cancellations",label:"Cancelamentos",helper:"Analisar e processar solicitações"},{flow:"privacy",label:"Privacidade",helper:"Solicitações de dados e LGPD"}];function Jr(){return e.jsx("div",{className:"py-10 text-center text-sm text-muted-foreground",children:"Carregando atendimentoâ¦"})}function Yr(){const[a,i]=Kt(),d=a.get("flow"),u=Ea.some(c=>c.flow===d)?d:null,p=Ea.find(c=>c.flow===u)||null,j=c=>{const l=new URLSearchParams(a);l.set("tab","protocolos"),l.set("sub","operar"),c?l.set("flow",c):l.delete("flow"),i(l,{replace:!0})},v=()=>{const c=new URLSearchParams(a);c.set("tab","protocolos"),c.set("sub","busca"),c.delete("flow"),i(c,{replace:!0})};return!u||!p?e.jsxs("section",{className:"overflow-hidden rounded-xl border border-border/60 bg-card","aria-label":"Tipos de atendimento",children:[e.jsxs("div",{className:"border-b border-border/50 px-4 py-3 sm:px-5",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Selecione o serviço"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Abra somente o atendimento necessário. Todos os recursos continuam disponÃveis na área escolhida."})]}),e.jsx("div",{className:"divide-y divide-border/50",children:Ea.map(c=>e.jsxs("button",{type:"button",onClick:()=>j(c.flow),className:"group flex w-full items-center justify-between gap-3 px-4 py-3 text-left transition-colors hover:bg-muted/25 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary sm:px-5","aria-label":`Abrir ${c.label}`,children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-semibold text-foreground",children:c.label}),e.jsx("span",{className:"mt-0.5 block text-xs text-muted-foreground",children:c.helper})]}),e.jsx("span",{className:"shrink-0 text-xs font-medium text-primary group-hover:underline",children:"Abrir"})]},c.flow))})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(W,{className:"border-border/50 shadow-none",children:e.jsxs(X,{className:"flex flex-wrap items-center gap-3 p-3",children:[e.jsxs(g,{type:"button",size:"sm",variant:"ghost",onClick:()=>j(null),children:[e.jsx(Qt,{className:"mr-1 h-4 w-4"})," Serviços"]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-semibold",children:p.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:p.helper})]}),e.jsx(g,{type:"button",size:"sm",variant:"outline",onClick:v,children:"Consultar protocolos"})]})}),e.jsxs(r.Suspense,{fallback:e.jsx(Jr,{}),children:[u==="tickets"&&e.jsx(Ur,{embedded:!0}),u==="appointments"&&e.jsx(Gr,{embedded:!0}),u==="bes"&&e.jsx(Wr,{embedded:!0}),u==="cancellations"&&e.jsx(Xr,{embedded:!0}),u==="privacy"&&e.jsx(Zr,{embedded:!0})]})]})}const eo=["Agendamento","Voucher PAF/MG","Voucher (Código)","Contratação de Plano","CS Bem-Estar","Seguro","Atendimento (Ticket)","LGPD","Cancelamento","Indicação"],so=[25,50,100];function Ra(a,i=300){const[d,u]=r.useState(a);return r.useEffect(()=>{const p=window.setTimeout(()=>u(a),i);return()=>window.clearTimeout(p)},[a,i]),d}function Z(a,i=!1){if(!a)return"â";
12try{return new Date(a).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:i?"numeric":"2-digit",hour:"2-digit",minute:"2-digit"})}catch{return a}}function Je(a){if(!a)return"";const i=a.replace(/\D/g,"");return i.length!==11?a:`${i.slice(0,3)}.***.***-${i.slice(9)}`}function qa(a){const i=(a||"").replace(/\D/g,"");return i.length!==11?i||"CPF não disponÃvel":`${i.slice(0,3)}.${i.slice(3,6)}.${i.slice(6,9)}-${i.slice(9)}`}function ao(a){if(!a)return"";const i=a.replace(/\D/g,"");return i.length>=8?`â¢â¢â¢â¢â¢-${i.slice(-4)}`:"â¢â¢â¢â¢"}function le(a){if(!a)return"";const[i,d]=a.split("@");return d?`${i.length<=2?i:`${i.slice(0,2)}***`}@${d}`:a}function to(a){const i=a.replace(/\D/g,"");if(i.length!==11||/^(\d)\1{10}$/.test(i))return!1;const d=(u,p)=>{let j=0;for(const c of u)j+=Number(c)*p--;const v=j*10%11;return v===10?0:v};return d(i.slice(0,9),10)===Number(i[9])&&d(i.slice(0,10),11)===Number(i[10])}function qs({status:a}){const i=String(a||"").toLowerCase(),d=["approved","paid","won","active","scheduled","confirmed","completed","voucher_issued","resolved","closed","aprovado","concluido","pago"],u=["cancelled","rejected","no_show","lost","canceled","cancelado","rejeitado"],p=d.includes(i)?"default":u.includes(i)?"destructive":"secondary",j={pending:"Pendente",pending_pricing:"Aguardando valores",confirmed:"Confirmado",completed:"ConcluÃdo",resolved:"Resolvido",closed:"Encerrado",cancelled:"Cancelado",canceled:"Cancelado",approved:"Aprovado",rejected:"Rejeitado",scheduled:"Agendado",voucher_issued:"Voucher emitido",em_analise:"Em análise",recebido:"Recebido",aberto:"Aberto"};return e.jsx(T,{variant:p,className:"whitespace-nowrap text-[10px]",children:j[i]||a||"â"})}function ro(a){return a==="referrals"||a==="credentialing_requests"?"lead":"deal"}function Tt(a,i){return`https://cssaude.bitrix24.com.br/crm/${a}/details/${i}/`}function ve(a){return a?a instanceof Error?a.message:String((a==null?void 0:a.message)||a):""}function li(){var ct,dt,mt,ut,pt,xt,ht,ft,jt,gt,bt,vt,yt,_t,Nt,Ct,St,wt,kt,Mt,Ft;const a=vr(),{role:i,isMaster:d}=wr(),u=d||i==="gerente",[p,j]=Kt(),v=p.get("sub"),c=["busca","operar","clientes","conflitos","origens","hierarquia"].includes(String(v))?String(v):"clientes",[l,N]=r.useState(!u&&["conflitos","origens","hierarquia"].includes(c)?"clientes":c);r.useEffect(()=>{const s=p.get("sub")||"clientes";if(["busca","operar","clientes","conflitos","origens","hierarquia"].includes(s)){if(!u&&["conflitos","origens","hierarquia"].includes(s)){const t=new URLSearchParams(p);t.set("tab","protocolos"),t.set("sub","clientes"),t.delete("flow"),j(t,{replace:!0}),N("clientes");return}s!==l&&N(s)}},[p,l,u,j]);const[U,I]=r.useState(""),[G,J]=r.useState(""),ce=Ra(U.trim(),320),de=Ra(G.trim(),320),[n,F]=r.useState("all"),[V,as]=r.useState("newest"),[C,za]=r.useState(""),[ye,$a]=r.useState(""),[_e,O]=r.useState(0),[Ne,Ht]=r.useState(25),[Ce,me]=r.useState(0),[Se,Ut]=r.useState(25),[Ds,Gt]=r.useState(30),[Ta,Wt]=r.useState(!1),[o,ts]=r.useState(null),[rs,Da]=r.useState(null),[k,ue]=r.useState(null),[Te,te]=r.useState(!1),[os,we]=r.useState(""),is=Ra(os.trim(),280),[m,ke]=r.useState(null),[x,La]=r.useState(""),[D,Ls]=r.useState(""),[Me,Bs]=r.useState(""),[Ba,ns]=r.useState(""),[ls,Is]=r.useState("form"),[cs,ds]=r.useState(""),[De,Y]=r.useState(""),[ms,Fe]=r.useState(""),[io,Ia]=r.useState(""),[Le,Be]=r.useState(""),[pe,us]=r.useState(""),[Vs,ps]=r.useState(""),[Os,xs]=r.useState(""),[Qs,hs]=r.useState(""),[Ks,fs]=r.useState(""),[Hs,js]=r.useState(""),[Va,gs]=r.useState(""),[Oa,Us]=r.useState(""),[Gs,Ws]=r.useState(""),[Xs,Zs]=r.useState(""),[Js,Ys]=r.useState(""),[ea,sa]=r.useState(""),[aa,ta]=r.useState(""),[ra,oa]=r.useState(""),[Qa,ia]=r.useState(!1),[Ka,na]=r.useState(""),[Ie,bs]=r.useState(null),[Ha,vs]=r.useState(null),[Xt,la]=r.useState(""),[ys,Ve]=r.useState(""),[ca,Ua]=r.useState(!1),[Ga,xe]=r.useState(""),[da,Wa]=r.useState(!1),[ma,Xa]=r.useState(!1),[ua,Za]=r.useState(!1),[Ja,he]=r.useState(!1),[pa,fe]=r.useState(""),[xa,je]=r.useState(""),[ha,fa]=r.useState(!1),Pe=C?new Date(`${C}T00:00:00`).toISOString():null,Ae=ye?new Date(`${ye}T23:59:59.999`).toISOString():null,Oe=B({queryKey:["admin-manual-protocol-catalog"],staleTime:5*6e4,queryFn:async()=>{const{data:s,error:t}=await z.rpc("admin_manual_protocol_catalog");if(t)throw t;return s||[]}}),Ee=B({queryKey:["admin-manual-bes-catalog"],enabled:Te&&x==="bes",staleTime:5*6e4,queryFn:async()=>{const{data:s,error:t}=await se("send-ticket-notification",{body:{mode:"manual_protocol_bes_catalog"}});if(t||!(s!=null&&s.success))throw new Error((s==null?void 0:s.error)||(t==null?void 0:t.message)||"Não foi possÃvel carregar o catálogo CS BES.");return(s==null?void 0:s.benefits)||[]}}),L=B({queryKey:["admin-manual-fixed-bes-clinics",D,m==null?void 0:m.client_key],enabled:Te&&x==="appointment"&&D==="consulta_fix
12a_bes"&&!!m,staleTime:6e4,retry:1,refetchOnMount:"always",queryFn:async()=>{const{data:s,error:t}=await se("send-ticket-notification",{body:{mode:"manual_protocol_fixed_bes_clinics",client_key:m.client_key}});if(t||!(s!=null&&s.success))throw new Error((s==null?void 0:s.error)||(t==null?void 0:t.message)||"Não foi possÃvel carregar as clÃnicas de Consulta Fixa BES.");return(s==null?void 0:s.clinics)||[]}}),Qe=B({queryKey:["admin-manual-provider-catalog"],enabled:Te&&x==="appointment"&&D!=="consulta_fixa_bes",staleTime:5*6e4,queryFn:async()=>{const{data:s,error:t}=await se("send-ticket-notification",{body:{mode:"manual_protocol_provider_catalog"}});if(t||!(s!=null&&s.success))throw new Error((s==null?void 0:s.error)||(t==null?void 0:t.message)||"Não foi possÃvel carregar a rede credenciada.");return(s==null?void 0:s.providers)||[]}}),ge=B({queryKey:["admin-manual-protocol-client-search",is],enabled:Te&&(is.length>=2||be(is).length>=3),staleTime:2e4,queryFn:async()=>{const{data:s,error:t}=await se("send-ticket-notification",{body:{mode:"manual_protocol_client_search",query:is}});if(t||!(s!=null&&s.success))throw new Error((s==null?void 0:s.error)||(t==null?void 0:t.message)||"Não foi possÃvel localizar beneficiários.");return(s==null?void 0:s.clients)||[]}}),Ya=(Oe.data||[]).filter(s=>s.manual_allowed),Zt=ge.data||[],_s=be(os),ja=to(_s),ga=_s.length===11&&!ja,et=!m&&!ge.isFetching&&Zt.length===0&&ja,Ke=m?x?3:2:1,re=Ya.find(s=>s.protocol_type===x)||null,st=(re==null?void 0:re.reasons)||[],S=(Ee.data||[]).find(s=>s.benefit_type===Me)||null,ba=Number(String(Ba).replace(",",".")),Jt=x!=="bes"||!(S!=null&&S.requires_requested_amount)||Number.isFinite(ba)&&ba>0,Ns=(L.data||[]).find(s=>s.id===cs)||null,va=Qe.data||[],Yt=Array.from(new Set(va.map(s=>s.state).filter(Boolean))).sort(),er=Array.from(new Set(va.filter(s=>!pe||s.state===pe).map(s=>s.city).filter(Boolean))).sort(),at=va.filter(s=>(!pe||s.state===pe)&&(!Le||s.city===Le)),oe=at.find(s=>s.id===ms)||null,Cs=be((m==null?void 0:m.display_cpf)||"").length===11,ya=["appointment","support_ticket","referral"].includes(x),tt=!!(m!=null&&m.display_email)&&m.display_email.includes("@"),sr=!!(m!=null&&m.display_phone)&&m.display_phone.trim().length>0,He=!!m&&!tt,Ss=!!m&&!sr,ar=Cs&&(He||Ss),Q=x==="appointment"&&D==="consulta_fixa_bes",tr=x==="appointment"&&["consulta","exame"].includes(D),Ue=Hs.trim()===""?null:Number(Hs),_a=Number(Va),rr=Q&&!!Qs&&!!Ks&&Number.isFinite(_a)&&_a>0&&(Ue==null||Number.isFinite(Ue)&&Ue>=0),or=x!=="appointment"||(Q?!!cs&&!!De&&rr:tr&&!!ms&&!!Le&&!!pe&&!!De&&!!Vs&&!!Os),ir=x!=="support_ticket"||!!Gs&&Xs.trim().length>=5,nr=x!=="referral"||!!Js&&ea.trim().length>=2&&(!!aa.trim()||!!ra.trim()),rt=!!m&&Cs&&!!x&&!!D&&(x!=="bes"||!!Me&&!!ls&&Jt)&&or&&ir&&nr&&(!ya||tt)&&!da&&!Ie,Re=B({queryKey:["admin-protocol-overview"],staleTime:3e4,queryFn:async()=>{const{data:s,error:t}=await z.rpc("admin_protocol_overview");if(t)throw t;return s||null}}),ie=B({queryKey:["admin-protocols-page",_e,Ne,n,Pe,Ae,ce,V],enabled:l==="busca",staleTime:15e3,queryFn:async()=>{let s=z.from("admin_protocols_presentation_effective").select("*",{count:"exact"}).order("created_at",{ascending:V==="oldest"}).range(_e*Ne,_e*Ne+Ne-1);if(n!=="all"&&(s=s.eq("source",n)),Pe&&(s=s.gte("created_at",Pe)),Ae&&(s=s.lte("created_at",Ae)),ce){const _=qt(ce),H=be(ce),ee=[];_&&ee.push(`protocol.ilike.%${_}%`,`subject_name.ilike.%${_}%`,`subject_email.ilike.%${_}%`,`ref_id.ilike.%${_}%`),H.length>=3&&ee.push(`subject_cpf_digits.ilike.%${H}%`),ee.length&&(s=s.or(ee.join(",")))}const{data:t,count:h,error:M}=await s;if(M)throw M;return{rows:t||[],total:h||0}}}),ne=B({queryKey:["admin-protocol-clients",Ce,Se,Pe,Ae,de],enabled:l==="clientes",staleTime:15e3,queryFn:async()=>{let s=z.from("admin_clients_history").select("*",{count:"exact"}).order("last_interaction_at",{ascending:!1}).range(Ce*Se,Ce*Se+Se-1);if(Pe&&(s=s.gte("last_interaction_at",Pe)),Ae&&(s=s.lte("last_interaction_at",Ae)),de){const _=qt(de),H=be(de),ee=[];_&&ee.push(`display_name.ilike.%${_}%`,`display_email.ilike.%${_}%`,`client_key.ilike.%${_.toLowerCase()}%`),H.length>=3&&ee.push(`display_cpf.ilike.%${H}%`),ee.length&&(s=s.or(ee.join(",")))}const{data:t,count:h,error:M}=await s;if(M)throw M;return{rows:t||[],total:h||0}}}),Ge=B({queryKey:["admin-protocol-conflicts"],enabled:l==="conflitos",staleTime:6e4,queryFn:async()=>{const{data:s,error:t}=await z.from("admin_protocols_presentation_effective").select("protocol,source").not("protocol","is",null).limit(1e4);if(t)throw t;const h=new Map,M=new Map;for(const _ of s||[]){if(!_.protocol)continue;h.set(_.protocol,(h.get(_.protocol)||0)+1);const H=M.get(_.protocol)||new Set;H.add(_.source),M.set(_.protocol,H)}return Array.from(h.entries()).filter(([,_])=>_>1).map(([_,H])=>({protocol:_,count:H,sources:Array.from(M.get(_)||[])})).sort((_,H)=>H.count-_.count)}}),We=B({queryKey:["admin-protocol-sources",Ds],enabled:l==="origens",staleTime:3e4,queryFn:async()=>{const{data:s,error:t}=await z.rpc("admin_protocols_by_source",{days:Ds});if(t)throw t;return s||[]}}),w=B({queryKey:["admin-manual-protocol-detail",o==null?void 0:o.ref_id],enabled:!!(o!=null&&o.ref_id)&&(o==null?void 0:o.source_table)==="admin_manual_protocols",staleTime:1e4,queryFn:async()=>{const{data:s,error:t}=await z.from("admin_manual_protocols").select("id,protocol,protocol_type,reason_code,reason_label,primary_protocol,notification_status,notification_sent_at,notification_error,notification_attempts,client_source,created_by_email,bitrix_deal_id,bitrix_contact_id,bitrix_category_id,bitrix_stage_id,bitrix_sync_status,bitrix_sync_error,bitrix_sync_attempts,bitrix_synced_at").eq("id",o.ref_id).single();if(t)throw t;return s}}),ot=B({queryKey:["admin-protocol-voucher",o==null?void 0:o.ref_id],enabled:(o==null?void 0:o.source_table)==="appointments"&&!!(o!=null&&o.ref_id),staleTime:15e3,queryFn:async()=>{const{data:s,error:t}=await z.from("appointments").select("voucher_issued_at,voucher_generated_at").eq("id",o.ref_id).maybeSingle();return t?null:s}}),Na=(o==null?void 0:o.client_key)||(k==null?void 0:k.client_key)||null,qe=B({queryKey:["admin-protocol-client-history",Na],enabled:!!Na,staleTime:2e4,queryFn:async()=>{const{data:s,error:t}=await z.from("admin_protocols_presentation_effective").select("*").eq("client_key",Na).order("created_at",{ascending:!1}).limit(200);if(t)throw t;return s||[]}}),Ca=((ct=ie.data)==null?void 0:ct.total)||0,Sa=((dt=ie.data)==null?void 0:dt.rows)||[],wa=((mt=ne.data)==null?void 0:mt.total)||0,ka=((ut=ne.data)==null?void 0:ut.rows)||[],K=Re.data,it=Ge.data||[],nt=We.data||[],ws=Math.max(1,Math.ceil(Ca/Ne)),ks=Math.max(1,Math.ceil(wa/Se));r.useEffect(()=>{_e>ws-1&&O(Math.max(0,ws-1))},[_e,ws]),r.useEffect(()=>{Ce>ks-1&&me(Math.max(0,ks-1))},[Ce,ks]),r.useEffect(()=>O(0),[ce]),r.useEffect(()=>me(0),[de]),r.useEffect(()=>{const s=[Re.error,ie.error,ne.error,Ge.error,We.error,qe.error,Oe.error,Ee.error,L.error,Qe.error,ge.error,w.error].map(ve).filter(
12Boolean);if(!s.length)return;const t=s[0];if(/forbidden|sessão administrativa forte|strong/i.test(t)){b.error("Sua sessão administrativa precisa de nova verificação em duas etapas.",{id:"protocol-admin-strong-session"}),window.location.assign("/auth?reauth=strong");return}b.error(t,{id:`protocol-admin-error-${t}`})},[Re.error,ie.error,ne.error,Ge.error,We.error,qe.error,Oe.error,Ee.error,L.error,Qe.error,ge.error,w.error]);const lr=async()=>{const s=[Re.refetch()];l==="busca"&&s.push(ie.refetch()),l==="clientes"&&s.push(ne.refetch()),l==="conflitos"&&s.push(Ge.refetch()),l==="origens"&&s.push(We.refetch()),await Promise.all(s),b.success("Protocolos atualizados")},cr=()=>{as("newest"),F("all"),za(""),$a(""),O(0),me(0)},Xe=s=>{ue(null),ts(s)},lt=s=>{ts(null),ue(s)},dr=s=>{ze(),we(s.display_cpf||s.display_email||s.display_name||""),ue(null),te(!0)},Ms=s=>{navigator.clipboard.writeText(s).then(()=>b.success("Copiado"),()=>b.error("Não foi possÃvel copiar"))},ze=()=>{we(""),ke(null),La(""),Ls(""),Bs(""),ns(""),Is("form"),ds(""),Y(""),Fe(""),Ia(""),Be(""),us(""),ps(""),xs(""),hs(""),fs(""),js(""),gs(""),Us(""),Ws(""),Zs(""),Ys(""),sa(""),ta(""),oa(""),ia(!1),na(""),bs(null),vs(null),la(""),Ve(""),xe(""),he(!1),fe(""),je(""),fa(!1)},mr=async s=>{const t=s.trim().toUpperCase();if(!t)return;te(!1),N("busca"),I(t),O(0);const{data:h,error:M}=await z.from("admin_protocols_presentation_effective").select("*").eq("protocol",t).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(!M&&h){ue(null),ts(h);return}b.info(`Protocolo ${t} localizado na fila.`)},ur=async()=>{if(!ja||!ys||ca){ga&&xe("CPF inválido. Confira os dÃgitos antes de consultar a AGSI.");return}Ua(!0),xe("");try{const{data:s,error:t}=await se("send-ticket-notification",{body:{mode:"manual_protocol_beneficiary_fallback",cpf:_s,birth_date:ys}});if(t||!(s!=null&&s.success)||!(s!=null&&s.client))throw new Error((s==null?void 0:s.error)||(t==null?void 0:t.message)||"Beneficiário não localizado.");ke(s.client),he(!1),fe(""),je(""),we(s.client.display_name||s.client.display_cpf||_s),Ve(""),b.success(s.source==="agsi_login_fallback"?"Beneficiário confirmado na AGSI e cadastro atualizado.":"Beneficiário localizado na base local.")}catch(s){const t=ve(s)||"Não foi possÃvel validar o beneficiário.";xe(t),b.error(t)}finally{Ua(!1)}},Fs=async()=>{var M;const{data:{session:s}}=await z.auth.getSession();if(!(s!=null&&s.access_token))return b.error("Sua sessão administrativa expirou. Faça a verificação novamente."),window.location.assign("/auth?reauth=strong"),!1;const{data:t,error:h}=await z.functions.invoke("admin-check",{headers:{Authorization:`Bearer ${s.access_token}`}});return h||!(t!=null&&t.is_admin)||((M=t==null?void 0:t.security_assurance)==null?void 0:M.strong)===!1?(b.error("Sua sessão administrativa precisa de nova verificação em duas etapas."),window.location.assign("/auth?reauth=strong"),!1):!0},pr=async()=>{if(!m||!Cs||ha)return;const s=pa.trim().toLowerCase(),t=xa.trim();if(!s&&!t){b.error("Informe o contato que está faltando.");return}if(s&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s)){b.error("Informe um e-mail válido.");return}fa(!0);try{if(!await Fs())return;const{data:h,error:M}=await se("send-ticket-notification",{body:{mode:"manual_protocol_fill_missing_contact",cpf:be(m.display_cpf||""),email:He?s:"",phone:Ss?t:""}});if(M||!(h!=null&&h.success)||!(h!=null&&h.client))throw new Error((h==null?void 0:h.error)||(M==null?void 0:M.message)||"Não foi possÃvel atualizar o contato.");ke(_=>_?{..._,...h.client}:h.client),he(!1),fe(""),je(""),await a.invalidateQueries({queryKey:["admin-manual-protocol-client-search"]}),b.success(h.already_current?"Contato sincronizado com a AGSI.":"Contato atualizado na AGSI.")}catch(h){b.error(ve(h)||"Não foi possÃvel atualizar o contato.")}finally{fa(!1)}},xr=async()=>{if(!(!rt||!m)){Wa(!0);try{if(!await Fs())return;const{data:s,error:t}=await se("send-ticket-notification",{body:{mode:"manual_protocol",client_key:m.client_key,protocol_type:x,reason_code:D,bes_benefit_type:x==="bes"?Me:void 0,bes_requested_amount_v2:x==="bes"?!0:void 0,bes_requested_amount:x==="bes"&&(S!=null&&S.requires_requested_amount)?ba:void 0,bes_submission_channel:x==="bes"?ls:void 0,appointment_clinic_id:x==="appointment"&&cs||void 0,appointment_specialty:x==="appointment"?De:void 0,appointment_provider_id:x==="appointment"&&D!=="consulta_fix
12a_bes"&&ms||void 0,appointment_financial_v3:Q||void 0,appointment_schedule_v4:Q||void 0,appointment_scheduled_date:Q?Qs:void 0,appointment_scheduled_time:Q?Ks:void 0,appointment_coparticipation_value:Q&&Ue!=null?Ue:void 0,appointment_client_paid_value:Q?_a:void 0,appointment_period:x==="appointment"&&!Q?Vs:void 0,appointment_days:x==="appointment"&&!Q?Os:void 0,appointment_notes:x==="appointment"&&Oa||void 0,ticket_subject:x==="support_ticket"?Gs:void 0,ticket_category:x==="support_ticket"?D:void 0,ticket_description:x==="support_ticket"?Xs:void 0,referral_type:x==="referral"?Js:void 0,referral_name:x==="referral"?ea:void 0,referral_contact:x==="referral"&&aa||void 0,referral_email:x==="referral"&&ra||void 0,referral_consent:x==="referral"?Qa:void 0,referral_message:x==="referral"&&Ka||void 0}});if((s==null?void 0:s.code)==="benefit_limit_reached"){const h=String((s==null?void 0:s.existing_protocol)||"").trim();b.info("Solicitação BES já existente no perÃodo permitido",{description:String((s==null?void 0:s.error)||"Este benefÃcio já atingiu o limite de solicitações do perÃodo."),action:h?{label:"Abrir protocolo",onClick:()=>{mr(h)}}:void 0}),te(!1),ze();return}if(t||!(s!=null&&s.success)||!(s!=null&&s.protocol_created))throw new Error((s==null?void 0:s.error)||(t==null?void 0:t.message)||"Não foi possÃvel criar o protocolo");if(s.deduplicated)b.info(`Solicitação já criada: ${s.protocol}. O mesmo protocolo foi reutilizado.`);else if(s.notification_sent&&(s.crm_synced||s.crm_pending)){const h=s.submission_channel==="form"?"formulário encaminhado; C41 será reconciliado após a conclusão documental":s.crm_pending?"CRM em processamento":"CRM sincronizado";b.success(`Protocolo ${s.protocol} criado â ${h} e cliente notificado.`)}else{const h=[!s.crm_synced&&!s.crm_pending?"CRM requer atenção":s.crm_pending?"CRM em processamento":"",s.notification_skipped?"cliente sem e-mail":"",!s.notification_sent&&!s.notification_skipped?"e-mail pendente de retry":""].filter(Boolean).join(" · ");b.warning(`Protocolo ${s.protocol} criado${h?` â ${h}.`:"."}`)}x==="bes"&&ls==="form"&&(s!=null&&s.program_form)&&(s!=null&&s.form_prefill)?(vs({id:String(s.program_form.id),sec:String(s.program_form.sec),loaderUrl:String(s.program_form.loader_url)}),la(String(s.upload_form_url||"https://csgrupo.bitrix24.site/programabes/")),bs({protocol:String(s.protocol),benefitType:Me,benefitLabel:String(s.benefit_label||(S==null?void 0:S.label)||Me),requiredDocuments:s.required_documents||(S==null?void 0:S.documents)||null,prefill:s.form_prefill})):(te(!1),ze()),O(0),await Promise.all([a.invalidateQueries({queryKey:["admin-protocol-overview"]}),a.invalidateQueries({queryKey:["admin-protocols-page"]}),a.invalidateQueries({queryKey:["admin-protocol-clients"]}),a.invalidateQueries({queryKey:["admin-protocol-conflicts"]}),a.invalidateQueries({queryKey:["admin-protocol-sources"]}),a.invalidateQueries({queryKey:["admin-protocol-hierarchy-v2"]})])}catch(s){const t=ve(s)||"Não foi possÃvel criar o protocolo.";if(/sessão administrativa forte|forbidden|strong/i.test(t)){b.error("Sua sessão administrativa perdeu a validação forte. Faça a verificação novamente."),window.location.assign("/auth?reauth=strong");return}b.error(t)}finally{Wa(!1)}}},hr=async()=>{if(!(!(o!=null&&o.protocol)||o.source_table!=="admin_manual_protocols"||ua)){Za(!0);try{if(!await Fs())return;const{data:s,error:t}=await se("send-ticket-notification",{body:{mode:"manual_protocol_retry",protocol:o.protocol}});if(t||!(s!=null&&s.success))throw new Error((s==null?void 0:s.error)||(t==null?void 0:t.message)||"Falha ao reenviar");s.notification_sent?b.success("Envio solicitado ao Resend. A entrega pode ser acompanhada no provedor."):s.notification_skipped?b.warning("Cliente sem e-mail válido; envio permanece não aplicável."):b.warning(s.notification_error||"O envio ainda não foi concluÃdo."),await w.refetch()}catch(s){b.error(ve(s)||"Não foi possÃvel reenviar o e-mail.")}finally{Za(!1)}}},fr=async()=>{if(!(!(o!=null&&o.protocol)||o.source_table!=="admin_manual_protocols"||ma)){Xa(!0);try{if(!await Fs())return;const{data:s,error:t}=await se("send-ticket-notification",{body:{mode:"manual_protocol_crm_retry",protocol:o.protocol}});if(t||!(s!=null&&s.success)||!(s!=null&&s.crm_synced))throw new Error((s==null?void 0:s.crm_error)||(s==null?void 0:s.error)||(t==null?void 0:t.message)||"Falha ao sincronizar CRM");b.success(`CRM sincronizado no deal ${s.bitrix_deal_id}.`),await w.refetch()}catch(s){b.error(ve(s)||"Não foi possÃvel sincronizar o CRM.")}finally{Xa(!1)}}},jr=s=>{window.open(`/autorizador?protocol=${encodeURIComponent(s)}`,"_blank","noopener,noreferrer")},gr=l==="clientes"?G:U,br=l==="clientes"?J:I,Ps=l==="busca"||l==="clientes",Ma=s=>{N(s);const t=new URLSearchParams(p);t.set("tab","protocolos"),t.set("sub",s),s!=="operar"&&t.delete("flow"),j(t,{replace:!0})};return e.jsxs("div",{className:"mx-auto max-w-[1440px] space-y-4",children:[e.jsx(Fr,{stacked:!0,title:"Protocolos",description:"Localize beneficiários, consulte atendimentos e registre solicitações.",count:l==="clientes"?wa:l==="busca"?Ca:void 0,countLabel:l==="clientes"?"beneficiários":"protocolos",search:Ps?gr:void 0,onSearchChange:Ps?br:void 0,searchPlaceholder:l==="clientes"?"Buscar beneficiário, CPF ou e-mailâ¦":"Buscar protocolo ou clienteâ¦",subline:e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-muted-foreground",children:[typeof(K==null?void 0:K.root_open)=="number"&&e.jsxs("span",{children:[e.jsx("strong",{className:"font-semibold tabular-nums text-foreground",children:K.root_open.toLocaleStr
12ing("pt-BR")})," protocolos em aberto"]}),typeof(K==null?void 0:K.operational_24h)=="number"&&e.jsxs("span",{children:[e.jsx("strong",{className:"font-semibold tabular-nums text-foreground",children:K.operational_24h.toLocaleString("pt-BR")})," registros nas últimas 24h"]}),u&&!!(K!=null&&K.conflicts)&&e.jsxs("button",{type:"button",onClick:()=>Ma("conflitos"),className:"font-medium text-amber-700 underline-offset-2 hover:underline dark:text-amber-400",children:[K.conflicts," possÃveis duplicidades para revisar"]})]}),right:Ps?e.jsxs(g,{size:"sm",variant:Ta||l==="busca"&&(n!=="all"||V!=="newest")||C||ye?"secondary":"outline",onClick:()=>Wt(s=>!s),className:"gap-1.5",children:[e.jsx(kr,{className:"h-3.5 w-3.5"}),"Filtros",(l==="busca"&&(n!=="all"||V!=="newest")||C||ye)&&e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-cs-orange","aria-hidden":!0})]}):void 0,actions:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(g,{size:"sm",onClick:()=>{ze(),te(!0)},disabled:Oe.isLoading,children:"Novo protocolo"}),e.jsx(g,{size:"icon",variant:"ghost",onClick:lr,disabled:Re.isFetching,title:"Atualizar","aria-label":"Atualizar protocolos",className:"h-8 w-8",children:e.jsx(es,{className:`h-3.5 w-3.5 ${Re.isFetching?"animate-spin":""}`})})]})}),e.jsxs(Mr,{value:l,onValueChange:Ma,syncParam:null,maxVisible:3,items:[{value:"clientes",label:"Beneficiários"},{value:"busca",label:"Protocolos"},{value:"operar",label:"Operações"},...u?[{value:"conflitos",label:"PossÃveis duplicidades"},{value:"origens",label:"Canais de entrada"},{value:"hierarquia",label:"VÃnculos e histórico"}]:[]],children:[e.jsx("p",{className:"mb-3 px-1 text-xs text-muted-foreground",children:l==="clientes"?"Localize a pessoa e abra seu histórico para consultar ou continuar o atendimento.":l==="busca"?"Consulte protocolos pelo número, beneficiário ou CPF. Abra para ver andamento, documentos e ações.":l==="operar"?"Escolha o tipo de atendimento. Todos os serviços continuam disponÃveis.":"Informações de conferência e acompanhamento administrativo."}),Ps&&Ta&&e.jsx("div",{className:"mb-3 rounded-xl border border-border/40 bg-muted/[0.16] p-3",children:e.jsxs("div",{className:`grid gap-2 sm:grid-cols-2 ${l==="busca"?"lg:grid-cols-[minmax(160px,1fr)_150px_150px_160px_auto]":"lg:grid-cols-[160px_160px_auto]"} lg:items-end`,children:[l==="busca"&&e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-[11px] font-medium text-muted-foreground",children:"Canal"}),e.jsxs(P,{value:n,onValueChange:s=>{F(s),O(0)},children:[e.jsx(A,{className:"h-9",children:e.jsx(E,{placeholder:"Todos os canais"})}),e.jsxs(R,{children:[e.jsx(f,{value:"all",children:"Todos os canais"}),eo.map(s=>e.jsx(f,{value:s,children:s},s))]})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-[11px] font-medium text-muted-foreground",children:"De"}),e.jsx($,{type:"date",className:"h-9",value:C,onChange:s=>{za(s.target.value),O(0),me(0)}})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-[11px] font-medium text-muted-foreground",children:"Até"}),e.jsx($,{type:"date",className:"h-9",value:ye,onChange:s=>{$a(s.target.value),O(0),me(0)}})]}),l==="busca"&&e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-[11px] font-medium text-muted-foreground",children:"Ordenar"}),e.jsxs(P,{value:V,onValueChange:s=>{as(s),O(0)},children:[e.jsx(A,{className:"h-9",children:e.jsx(E,{})}),e.jsxs(R,{children:[e.jsx(f,{value:"newest",children:"Mais recentes"}),e.jsx(f,{value:"oldest",children:"Mais antigos"})]})]})]}),e.jsxs(g,{size:"sm",variant:"ghost",className:"h-9 justify-start lg:justify-center",onClick:cr,disabled:(l!=="busca"||n==="all"&&V==="newest")&&!C&&!ye,children:[e.jsx(yr,{className:"mr-2 h-3.5 w-3.5"})," Limpar"]})]})}),e.jsxs($e,{value:"busca",className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:[{value:"all",label:"Tudo"},{value:"Atendimento (Ticket)",label:"Atendimento"},{value:"Agendamento",label:"Agendamentos"},{value:"CS Bem-Estar",label:"CS Bem-Estar"}].map(s=>e.jsx(g,{type:"button",size:"sm",variant:n===s.value?"secondary":"outline",onClick:()=>{F(s.value),O(0)},className:"h-8",children:s.label},s.value))}),e.jsx(W,{className:"overflow-hidden border-border/40",children:e.jsx(X,{className:"p-0",children:ie.isLoading||ie.isFetching&&!ie.data?e.jsx(Ye,{label:"Carregando protocolosâ¦"}):Sa.length===0?e.jsx(zs,{title:"Nenhum protocolo encontrado",description:"Ajuste a busca, a origem ou o perÃodo informado."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"divide-y divide-border/40 md:hidden",children:Sa.map(s=>e.jsxs("button",{type:"button",onClick:()=>Xe(s),className:"w-full p-3 text-left transition-colors hover:bg-muted/20",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("code",{className:"block truncate text-xs font-semibold",children:s.protocol||"â"}),e.jsx("div",{className:"mt-1 truncate text-sm font-medium",children:s.subject_name||"Cliente"}),e.jsxs("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:[s.source," · ",Z(s.created_at)]})]}),e.jsx(qs,{status:s.status})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 text-[10px] text-muted-foreground",children:[e.jsx("span",{className:"truncate",children:s.subject_cpf?Je(s.subject_cpf):le(s.subject_email)}),e.jsx("span",{className:"shrink-0",children:"Abrir"})]})]},`mobile-${s.source_table}-${s.ref_id}-${s.protocol}`))}),e.jsx("div",{className:"hidden overflow-x-auto md:block",children:e.jsxs("table",{className:"w-full min-w-[720px] text-sm",children:[e.jsx("thead",{className:"border-b bg-muted/30 text-left text-[11px] uppercase tracking-wide text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 font-medium",children:"Protocolo e origem"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Beneficiário"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Status"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Criado em"}),e.jsx("th",{className:"px-4 py-3 text-right font-medium",children:"Ações"})]})}),e.jsx("tbody",{className:"divide-y divide-border/40",children:Sa.map(s=>e.jsxs("tr",{className:"transition-colors hover:bg-muted/20",children:[e.jsx("td",{className:"px-4 py-3",children:e.jsxs("button",{className:"text-left",onClick:()=>Xe(s),children:[e.jsx("code",{className:"text-xs font-semibold text-foreground",children:s.protocol||"â"}),e.jsx("span",{className:"mt-1 block text-[11px] text-muted-foreground",children:s.source})]})}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"max-w-56 truncate font-medium",title:s.subject_name||"",children:s.subject_name||"â"}),e.jsx("div",{className:"mt-0.5 text-[10px] text-muted-foreground",children:s.subject_cpf?Je(s.subject_cpf):le(s.subject_email)})]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(qs,{status:s.status})}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-xs text-muted-foreground",children:Z(s.created_at)}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(g,{size:"sm",variant:"ghost",onClick:()=>Xe(s),children:"Abrir"})})]},`${s.source_table}-${s.ref_id}-${s.protocol}`))})]})})]})})}),e.jsx(Dt,{page:_e,setPage:O,totalPages:ws,pageSize:Ne,setPageSize:s=>{Ht(s),O(0)},total:Ca})]}),e.jsx($e,{value:"operar",className:"space-y-3",children:e.jsx(Yr,{})}),e.jsxs($e,{value:"clientes",className:"space-y-3",children:[e.jsx(W,{className:"overflow-hidden border-border/40",children:e.jsx(X,{className:"p-0",children:ne.isLoading||ne.isFetching&&!ne.data?e.jsx(Ye,{label:"Carregando beneficiáriosâ¦"}
12):ka.length===0?e.jsx(zs,{title:"Nenhum beneficiário encontrado",description:"Ajuste a busca ou o perÃodo informado."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"divide-y divide-border/40 md:hidden",children:ka.map(s=>e.jsx("button",{type:"button",onClick:()=>lt(s),className:"w-full p-3 text-left transition-colors hover:bg-muted/20",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:s.display_name||"Beneficiário"}),e.jsxs("div",{className:"mt-1 text-[11px] text-muted-foreground",children:[qa(s.display_cpf),s.display_email&&e.jsx("div",{children:le(s.display_email)})]}),e.jsxs("div",{className:"mt-0.5 text-[10px] text-muted-foreground",children:["Ãltima interação ",Z(s.last_interaction_at)]})]}),e.jsx(T,{variant:"secondary",children:s.total_protocols})]})},`mobile-${s.client_key}`))}),e.jsx("div",{className:"hidden overflow-x-auto md:block",children:e.jsxs("table",{className:"w-full min-w-[820px] text-sm",children:[e.jsx("thead",{className:"border-b bg-muted/30 text-left text-[11px] uppercase tracking-wide text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 font-medium",children:"Beneficiário"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Identificação"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Protocolos"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Canais"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Ãltima interação"}),e.jsx("th",{className:"px-4 py-3 text-right font-medium",children:"Ação"})]})}),e.jsx("tbody",{className:"divide-y divide-border/40",children:ka.map(s=>e.jsxs("tr",{className:"transition-colors hover:bg-muted/20",children:[e.jsx("td",{className:"px-4 py-3",children:e.jsx("div",{className:"max-w-64 truncate font-medium",children:s.display_name||"Beneficiário"})}),e.jsxs("td",{className:"px-4 py-3 text-xs text-muted-foreground",children:[e.jsx("div",{children:qa(s.display_cpf)}),s.display_email?e.jsx("div",{children:le(s.display_email)}):null]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(T,{variant:"secondary",children:s.total_protocols})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("div",{className:"max-w-64 truncate text-xs text-muted-foreground",title:(s.sources||[]).join(", "),children:(s.sources||[]).join(", ")||"â"})}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-xs text-muted-foreground",children:Z(s.last_interaction_at)}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(g,{size:"sm",variant:"ghost",onClick:()=>lt(s),children:"Abrir histórico"})})]},s.client_key))})]})})]})})}),e.jsx(Dt,{page:Ce,setPage:me,totalPages:ks,pageSize:Se,setPageSize:s=>{Ut(s),me(0)},total:wa})]}),e.jsx($e,{value:"conflitos",children:e.jsxs(W,{className:"border-border/40",children:[e.jsxs($s,{className:"pb-3",children:[e.jsxs(Ts,{className:"flex items-center gap-2 text-base",children:[e.jsx(_r,{className:"h-4 w-4 text-amber-600"})," Protocolos duplicados entre fontes"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Detecta códigos repetidos no conjunto operacional. Nenhum registro é alterado por esta análise."})]}),e.jsx(X,{children:Ge.isLoading?e.jsx(Ye,{compact:!0,label:"Verificando conflitosâ¦"}):it.length===0?e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-emerald-500/20 bg-emerald-500/5 p-4 text-sm",children:[e.jsx(It,{className:"h-4 w-4 text-emerald-600"})," Nenhum protocolo duplicado encontrado."]}):e.jsx("div",{className:"space-y-2",children:it.map(s=>e.jsxs("div",{className:"flex flex-col gap-2 rounded-lg border border-amber-500/20 p-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("code",{className:"text-xs font-semibold",children:s.protocol}),e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:s.sources.join(" · ")})]}),e.jsxs(T,{variant:"destructive",children:[s.count," ocorrências"]})]},s.protocol))})})]})}),e.jsx($e,{value:"origens",children:e.jsxs(W,{className:"border-border/40",children:[e.jsxs($s,{className:"flex flex-row items-start justify-between gap-3 pb-3",children:[e.jsxs("div",{children:[e.jsxs(Ts,{className:"flex items-center gap-2 text-base",children:[e.jsx(Br,{className:"h-4 w-4 text-primary"})," Canais de entrada"]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Volume de protocolos por canal no perÃodo selecionado."})]}),e.jsxs(P,{value:String(Ds),onValueChange:s=>Gt(Number(s)),children:[e.jsx(A,{className:"h-8 w-[132px]",children:e.jsx(E,{})}),e.jsxs(R,{children:[e.jsx(f,{value:"7",children:"7 dias"}),e.jsx(f,{value:"30",children:"30 dias"}),e.jsx(f,{value:"90",children:"90 dias"}),e.jsx(f,{value:"365",children:"365 dias"})]})]})]}),e.jsx(X,{children:We.isLoading?e.jsx(Ye,{compact:!0,label:"Carregando origensâ¦"}):nt.length===0?e.jsx(zs,{compact:!0,title:"Sem registros no perÃodo",description:"Amplie a janela para visualizar outras origens."}):e.jsx("div",{className:"space-y-2",children:nt.map((s,t)=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/40 p-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:s.source_key}),e.jsxs("details",{className:"mt-1 text-[10px] text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer",children:"Detalhes"}),e.jsx("code",{children:s.source_table})]})]}),e.jsx(T,{variant:"secondary",className:"tabular-nums",children:Number(s.total).toLocaleStr
12ing("pt-BR")})]},`${s.source_key}-${s.source_table}-${t}`))})})]})}),e.jsx($e,{value:"hierarquia",className:"space-y-3",children:e.jsx(Hr,{})})]}),e.jsx(zr,{open:Te,onOpenChange:s=>{te(s),s||ze()},children:e.jsxs(Ar,{className:"w-[calc(100vw-1rem)] max-w-4xl",children:[e.jsxs($r,{className:"space-y-2 border-b border-border/50 pb-3",children:[e.jsx(Tr,{children:"Novo protocolo"}),e.jsx(Dr,{children:"Identifique o beneficiário, selecione o atendimento e confira os dados antes de registrar."}),e.jsx("ol",{className:"flex flex-wrap items-center gap-x-4 gap-y-1.5 pt-1 text-[11px]","aria-label":"Progresso da solicitação",children:[{step:1,label:"Beneficiário"},{step:2,label:"Atendimento"},{step:3,label:"Conferência"}].map(s=>e.jsxs("li",{"aria-current":Ke===s.step?"step":void 0,className:Ke===s.step?"font-semibold text-foreground":"text-muted-foreground",children:[e.jsx("span",{className:`mr-1.5 inline-flex h-5 w-5 items-center justify-center rounded-full border text-[10px] ${Ke===s.step?"border-primary text-primary":"border-border/60"}`,children:s.step}),s.label]},s.step))})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[m?e.jsx("span",{className:"text-xs font-medium",children:"Beneficiário selecionado"}):e.jsx(y,{htmlFor:"manual-protocol-client-search",children:"Localizar beneficiário"}),m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{variant:"secondary",children:m.client_source==="agsi"||m.client_source==="agsi_mirror"?"Fonte oficial":m.client_source==="profile"?"Portal":"Histórico"}),e.jsx(g,{type:"button",size:"sm",variant:"ghost",className:"h-7 px-2 text-[11px]",onClick:()=>{ke(null),we(""),Ve(""),xe(""),he(!1),fe(""),je("")},children:"Trocar"})]})]}),!m&&e.jsx($,{id:"manual-protocol-client-search",value:os,onChange:s=>{we(s.target.value),ke(null),Ve(""),xe(""),he(!1),fe(""),je("")},placeholder:"Nome, CPF ou e-mail do beneficiário",autoComplete:"off"}),m?e.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/15 p-3",children:[e.jsx("div",{className:"font-medium",children:m.display_name||"Cliente CS Saúde"}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[e.jsx("span",{children:m.display_cpf?Je(m.display_cpf):"CPF não disponÃvel"}),m.display_email&&e.jsx("span",{children:le(m.display_email)}),m.display_phone&&e.jsx("span",{children:m.display_phone})]}),m.plan_name&&e.jsxs("details",{className:"mt-2 text-[11px] text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer",children:"Mais informações"}),e.jsxs("div",{className:"mt-1",children:["Plano: ",m.plan_name]})]}),!Cs&&e.jsx("div",{className:"mt-2 text-xs text-destructive",children:"CPF não disponÃvel para criar o protocolo."}),ar&&e.jsxs("div",{className:"mt-3 rounded-xl border border-amber-500/20 bg-background/70 p-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-xs font-medium text-foreground",children:"Contato incompleto"}),e.jsxs("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:[[He?"e-mail":"",Ss?"telefone":""].filter(Boolean).join(" e "),ya&&He?" · necessário para esta solicitação":""]})]}),e.jsx(g,{type:"button",size:"sm",variant:"ghost",className:"h-8 shrink-0 px-2 text-xs",onClick:()=>he(s=>!s),children:Ja?"Fechar":"Completar"})]}),Ja&&e.jsxs("div",{className:"mt-3 space-y-2 border-t border-border/40 pt-3",children:[He&&e.jsxs("div",{className:"relative",children:[e.jsx(Nr,{className:"absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx($,{type:"email",value:pa,onChange:s=>fe(s.target.value.slice(0,255)),placeholder:"E-mail",className:"h-9 pl-9"})]}),Ss&&e.jsxs("div",{className:"relative",children:[e.jsx(Cr,{className:"absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx($,{value:xa,onChange:s=>je(s.target.value.replace(/[^0-9()+\-\s]/g,"").slice(0,20)),placeholder:"Telefone / WhatsApp",inputMode:"tel",className:"h-9 pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("p",{className:"text-[10px] leading-relaxed text-muted-foreground",children:"Só campos vazios são preenchidos. A AGSI permanece como fonte oficial."}),e.jsx(g,{type:"button",size:"sm",onClick:pr,disabled:ha||!pa.trim()&&!xa.trim(),className:"h-8 shrink-0",children:ha?e.jsx(ae,{className:"h-3.5 w-3.5 animate-spin"}):"Salvar"})]})]})]})]}):e.jsx("div",{className:"max-h-52 space-y-1 overflow-y-auto rounded-lg border border-border/40 p-1",children:ge.isFetching?e.jsxs("div",{className:"flex items-center justify-center gap-2 py-5 text-xs text-muted-foreground",children:[e.jsx(ae,{className:"h-3.5 w-3.5 animate-spin"})," Buscando beneficiáriosâ¦"]}):(ge.data||[]).length>0?(ge.data||[]).map(s=>e.jsxs("button",{type:"button",disabled:be(s.display_cpf||"").length!==11,className:"w-full rounded-md px-3 py-2 text-left hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",onClick:()=>{ke(s),we(s.display_name||s.display_cpf||s.display_email||s.client_key),he(!1),fe(""),je("")},children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:s.display_name||"Cliente CS Saúde"}),e.jsx(T,{variant:"outline",className:"text-[10px]",children:s.client_source==="agsi"||s.client_source==="agsi_mirror"?"Fonte oficial":s.client_source==="profile"?"Portal":"Histórico"})]}),e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:[s.display_cpf?Je(s.display_cpf):"CPF não disponÃvel",s.display_email?le(s.display_email):"",s.plan_name||""].filter(
12Boolean).join(" · ")||s.client_key})]},`${s.client_source}-${s.source_id}-${s.client_key}`)):e.jsxs("div",{className:"space-y-3 p-3",children:[e.jsx("div",{className:`text-center text-xs ${ga?"text-destructive":"text-muted-foreground"}`,children:os.trim().length>=2?ga?"CPF inválido. Confira os 11 dÃgitos.":et?"Não encontrado. Confirme a data de nascimento para consultar a fonte oficial.":"Nenhum beneficiário encontrado. Tente nome completo, e-mail ou CPF.":"Digite ao menos 2 caracteres ou 3 dÃgitos."}),et&&e.jsxs("div",{className:"rounded-lg border border-amber-500/20 bg-amber-500/5 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2 text-xs font-medium",children:[e.jsx(Kr,{className:"h-3.5 w-3.5"}),"Consulta complementar"]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-[1fr_auto] sm:items-end",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(y,{htmlFor:"manual-protocol-birth",className:"text-[11px]",children:"Data de nascimento"}),e.jsx($,{id:"manual-protocol-birth",type:"date",value:ys,onChange:s=>{Ve(s.target.value),xe("")}})]}),e.jsx(g,{type:"button",variant:"outline",onClick:ur,disabled:!ys||ca,children:ca?e.jsxs(e.Fragment,{children:[e.jsx(ae,{className:"mr-2 h-4 w-4 animate-spin"})," Consultandoâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(Vt,{className:"mr-2 h-4 w-4"})," Validar beneficiário"]})})]}),e.jsx("p",{className:"mt-2 text-[10px] leading-relaxed text-muted-foreground",children:"A consulta é pontual, protegida por limite de uso e não armazena a data informada."}),Ga&&e.jsx("p",{className:"mt-2 text-[11px] text-destructive",children:Ga})]})]})})]}),m&&e.jsx(e.Fragment,{children:e.jsxs("section",{className:"grid gap-3 rounded-lg border border-border/60 bg-card p-3 sm:grid-cols-2","aria-label":"Tipo e detalhes do atendimento",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Tipo de solicitação"}),e.jsxs(P,{value:x,onValueChange:s=>{La(s),Ls(""),Bs(""),ns(""),Is("form"),ds(""),Y(""),Fe(""),Ia(""),Be(""),us(""),ps(""),xs(""),hs(""),fs(""),js(""),gs(""),Us(""),Ws(""),Zs(""),Ys(""),sa(""),ta(""),oa(""),ia(!1),na(""),bs(null),vs(null),la("")},children:[e.jsx(A,{children:e.jsx(E,{placeholder:"Selecione a solicitação"})}),e.jsx(R,{children:Ya.map(s=>e.jsx(f,{value:s.protocol_type,children:s.label},s.protocol_type))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Motivo"}),e.jsxs(P,{value:D,onValueChange:s=>{Ls(s),ds(""),Y(""),Fe(""),Be(""),us(""),ps(""),xs(""),hs(""),fs(""),js(""),gs("")},disabled:!re,children:[e.jsx(A,{children:e.jsx(E,{placeholder:"Selecione o motivo"})}),e.jsx(R,{children:st.map(s=>e.jsx(f,{value:s.code,children:s.label},s.code))})]})]}),x==="bes"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(y,{children:"BenefÃcio CS BES"}),e.jsxs(P,{value:Me,onValueChange:s=>{Bs(s),ns("")},disabled:Ee.isLoading,children:[e.jsx(A,{children:e.jsx(E,{placeholder:Ee.isLoading?"Carregando benefÃciosâ¦":"Selecione o benefÃcio"})}),e.jsx(R,{children:(Ee.data||[]).map(s=>e.jsx(f,{value:s.benefit_type,children:s.label},s.id))})]}),S&&e.jsxs("div",{className:"rounded-md bg-muted/40 p-3 text-xs text-muted-foreground",children:[S.requirement&&e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-foreground",children:"Regra:"})," ",S.requirement]}),S.documents&&e.jsxs("div",{className:"mt-1 line-clamp-4",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Documentação:"})," ",S.documents]})]})]}),(S==null?void 0:S.requires_requested_amount)&&e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(y,{htmlFor:"manual-bes-requested-amount",children:"Valor solicitado (R$)"}),e.jsx($,{id:"manual-bes-requested-amount",type:"number",inputMode:"decimal",min:"0.01",step:"0.01",value:Ba,onChange:s=>ns(s.target.value),onWheel:s=>s.currentTarget.blur(),placeholder:"0,00"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Informe somente o valor desta solicitação."})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(y,{children:"Envio de documentos"}),e.jsxs(P,{value:ls,onValueChange:s=>Is(s),children:[e.jsx(A,{children:e.jsx(E,{})}),e.jsxs(R,{children:[e.jsx(f,{value:"form",children:"Formulário online"}),e.jsx(f,{value:"email",children:"E-mail"})]})]}),e.jsxs("details",{className:"text-[11px] text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer",children:"Detalhes do fluxo"}),e.jsx("p",{className:"mt-1",children:"O protocolo é único. O formulário mantém o fluxo documental nativo; o e-mail utiliza a integração configurada."})]})]})]}),x==="appointment"&&!!D&&e.jsxs(e.Fragment,{children:[Q?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(y,{children:"ClÃnica"}),e.jsxs(P,{value:cs,onValueChange:s=>{ds(s),Y("")},disabled:L.isFetching||L.isError,children:[e.jsx(A,{children:e.jsx(E,{placeholder:L.isFetching?"Carregando clÃnicas elegÃveisâ¦":L.isError?"Falha ao carregar clÃnicas":(L.data||[]).length===0?"Nenhuma clÃnica elegÃvel":"Selecione a clÃnica"})}),e.jsx(R,{children:(L.data||[]).map(s=>e.jsxs(f,{value:s.id,children:[s.name,s.city?` · ${s.city}/${s.state||""}`:""]},s.id))})]}),L.isError&&e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md border border-destructive/20 bg-destructive/5 px-2.5 py-2 text-[11px] text-destructive",children:[e.jsx("span",{children:"Não foi possÃvel carregar as clÃnicas para este beneficiário."}),e.jsx(g,{type:"button",size:"sm",variant:"outline",className:"h-7",onClick:()=>void L.refetch(),children:"Tentar novamente"})]}),!L.isFetching&&!L.isError&&(L.data||[]).length===0&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Nenhuma clÃnica de Consulta Fixa BES está disponÃvel para este beneficiário no momento."})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(y,{children:"Especialidade"}),e.jsxs(P,{value:De,onValueChange:Y,disabled:!Ns,children:[e.jsx(A,{children:e.jsx(E,{placeholder:"Selecione a especialidade"})}),e.jsx(R,{children:((Ns==null?void 0:Ns.specialties)||[]).map(s=>e.jsx(f,{value:s,children:s},s))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{htmlFor:"manual-fixed-date",children:"Data"}),e.jsx($,{id:"manual-fixed-date",type:"date",value:Qs,onChange:s=>hs(s.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{htmlFor:"manual-fixed-time",children:"Hora"}),e.jsx($,{id:"manual-fixed-time",type:"time",value:Ks,onChange:s=>fs(s.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(y,{htmlFor:"manual-fixed-coparticipation",children:["Coparticipação CS Saúde (R$) ",e.jsx("span",{className:"text-muted-foreground",children:"(opcional)"})]}),e.jsx($,{id:"manual-fixed-coparticipation",type:"number",inputMode:"decimal",min:"0",step:"0.01",value:Hs,onChange:s=>js(s.target.value),onWheel:s=>s.currentTarget.blur(),placeholder:"0,00"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Valor que a CS Saúde repassa à clÃnica."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{htmlFor:"manual-fixed-client-paid",children:"Valor do Cliente (R$)"}),e.jsx($,{id:"manual-fixed-client-paid",type:"number",inputMode:"decimal",min:"0.01",step:"0.01",value:Va,onChange:s=>gs(s.target.value),onWheel:s=>s.currentTarget.blur(),placeholder:"0,00"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Valor que o cliente deverá pagar diretamente à clÃnica."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"UF"}),e.jsxs(P,{value:pe,onValueChange:s=>{us(s),Be(""),Fe(""),Y("")},children:[e.jsx(A,{children:e.jsx(E,{placeholder:"Selecione a UF"})}),e.jsx(R,{children:Yt.map(s=>e.jsx(f,{value:s,children:s},s))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Cidade"}),e.jsxs(P,{value:Le,onValueChange:s=>{Be(s),Fe(""),Y("")},disabled:!pe,children:[e.jsx(A,{children:e.jsx(E,{placeholder:"Selecione a cidade"})}),e.jsx(R,{children:er.map(s=>e.jsx(f,{value:s,children:s},s))})]})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(y,{children:"Prestador"}),e.jsxs(P,{value:ms,onValueChange:s=>{Fe(s),Y("")},disabled:!Le||Qe.isLoading,children:[e.jsx(A,{children:e.jsx(E,{placeholder:Qe.isLoading?"Carregando redeâ¦":"Selecione o prestador"})}),e.jsx(R,{children:at.map(s=>e.jsx(f,{value:s.id,children:s.name},s.id))})]}),(oe==null?void 0:oe.address)&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:oe.address})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(y,{children:"Especialidade ou serviço"}),e.jsxs(P,{value:De,onValueChange:Y,disabled:!oe,children:[e.jsx(A,{children:e.jsx(E,{placeholder:"Selecione"})}),e.jsx(R,{children:((oe==null?void 0:oe.specialties)||[]).map(s=>e.jsx(f,{value:s,children:s},s))})]})]})]}),!Q&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"PerÃodo"}),e.jsxs(P,{value:Vs,onValueChange:ps,children:[e.jsx(A,{children:e.jsx(E,{placeholder:"Preferência"})}),e.jsxs(R,{children:[e.jsx(f,{value:"morning",children:"Manhã"}),e.jsx(f,{value:"afternoon",children:"Tarde"}),e.jsx(f,{value:"evening",children:"Noite"}),e.jsx(f,{value:"any",children:"Qualquer perÃodo"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Dias"}),e.jsxs(P,{value:Os,onValueChange:xs,children:[e.jsx(A,{children:e.jsx(E,{placeholder:"Preferência"})}),e.jsxs(R,{children:[e.jsx(f,{value:"weekdays",children:"Dias de semana"}),e.jsx(f,{value:"weekend",children:"Final de semana"}),e.jsx(f,{value:"any",children:"Qualquer dia"})]})]})]})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(y,{children:"Observações (opcional)"}),e.jsx(Fa,{value:Oa,onChange:s=>Us(s.target.value),maxLength:1e3})]})]}),x==="support_ticket"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(y,{children:"Assu
12nto"}),e.jsxs(P,{value:Gs,onValueChange:Ws,children:[e.jsx(A,{children:e.jsx(E,{placeholder:"Selecione o assunto"})}),e.jsx(R,{children:["Suporte Técnico","Financeiro","Agendamentos","Parcerias","Cancelamento","Reembolso","Dúvidas sobre Planos","Outros"].map(s=>e.jsx(f,{value:s,children:s},s))})]})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(y,{children:"Descrição"}),e.jsx(Fa,{value:Xs,onChange:s=>Zs(s.target.value),maxLength:2e3,rows:4})]})]}),x==="referral"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(y,{children:"Tipo de indicação"}),e.jsxs(P,{value:Js,onValueChange:Ys,children:[e.jsx(A,{children:e.jsx(E,{placeholder:"Selecione"})}),e.jsxs(R,{children:[e.jsx(f,{value:"provider",children:"Prestador de saúde"}),e.jsx(f,{value:"client_b2c",children:"Cliente"}),e.jsx(f,{value:"company_b2b",children:"Empresa"}),e.jsx(f,{value:"commerce",children:"Comércio / parceiro"})]})]})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(y,{children:"Nome do indicado"}),e.jsx($,{value:ea,onChange:s=>sa(s.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"Telefone do indicado"}),e.jsx($,{value:aa,onChange:s=>ta(s.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(y,{children:"E-mail do indicado"}),e.jsx($,{type:"email",value:ra,onChange:s=>oa(s.target.value)})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:col-span-2",children:[e.jsx(Rr,{id:"manual-referral-consent",checked:Qa,onCheckedChange:s=>ia(s===!0)}),e.jsx(y,{htmlFor:"manual-referral-consent",className:"text-xs font-normal",children:"O beneficiário declarou autorização para compartilhar e eventualmente contatar o indicado por e-mail."})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(y,{children:"Observações (opcional)"}),e.jsx(Fa,{value:Ka,onChange:s=>na(s.target.value),maxLength:1e3,rows:3})]})]})]})}),Ie&&Ha&&e.jsx(qr,{target:Ie,formMeta:Ha,externalUrl:Xt,onSubmitted:async()=>{const{data:s,error:t}=await z.functions.invoke("send-ticket-notification",{body:{mode:"manual_protocol_bes_form_completed",protocol:Ie.protocol}});if(t||!(s!=null&&s.success))throw new Error((s==null?void 0:s.error)||(t==null?void 0:t.message)||"Não foi possÃvel vincular o formulário ao protocolo.");b.success(s.reconciled?`Formulário vinculado ao protocolo ${Ie.protocol}.`:"Formulário recebido; vÃnculo do C41 em processamento."),await Promise.all([a.invalidateQueries({queryKey:["admin-protocol-overview"]}),a.invalidateQueries({queryKey:["admin-protocols-page"]}),a.invalidateQueries({queryKey:["admin-protocol-hierarchy-v2"]})])},onClose:()=>{bs(null),vs(null),te(!1),ze()}}),m&&re&&e.jsxs("section",{className:"rounded-lg border border-border/60 bg-muted/15 p-3","aria-label":"Revisão do protocolo",children:[e.jsx("div",{className:"text-xs font-semibold",children:"Conferência antes do registro"}),e.jsxs("div",{className:"mt-2 grid gap-2 text-xs sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Beneficiário:"})," ",e.jsx("span",{className:"font-medium",children:m.display_name||"Cliente CS Saúde"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Solicitação:"})," ",e.jsx("span",{className:"font-medium",children:re.label})]}),D&&e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Motivo:"})," ",e.jsx("span",{className:"font-medium",children:((pt=st.find(s=>s.code===D))==null?void 0:pt.label)||D})]})]}),e.jsxs("details",{className:"mt-3 border-t border-border/40 pt-2 text-[11px] text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer font-medium text-foreground/80",children:"Detalhes do processamento"}),e.jsxs("div",{className:"mt-2 grid gap-1.5 sm:grid-cols-2",children:[e.jsxs("div",{children:["Prefixo: ",e.jsx("code",{children:re.prefix})]}),e.jsxs("div",{children:["Status inicial: ",re.initial_status]}),e.jsx("div",{children:"Acompanhamento: Atendimento Digital â Protocolos"}),e.jsxs("div",{children:["Notificação: ",ya?"obrigatória":"quando houver e-mail"]})]}),e.jsx("p",{className:"mt-2",children:"Voucher, autorização e ATD-R continuam exclusivamente automáticos."})]})]})]}),e.jsxs(Lr,{className:"sticky bottom-0 -mx-4 -mb-4 border-t bg-background/95 px-4 py-3 backdrop-blur sm:-mx-6 sm:-mb-6 sm:px-6",children:[e.jsx("div",{className:"mr-auto hidden text-[11px] text-muted-foreground sm:block",children:Ke===1?"Confirme o beneficiário.":Ke===2?"Escolha o atendimento.":"Revise os dados antes de registrar."}),e.jsx(g,{type:"button",variant:"outline",onClick:()=>te(!1),disabled:da,children:"Cancelar"}),e.jsx(g,{type:"button",onClick:xr,disabled:!rt,children:da?e.jsxs(e.Fragment,{children:[e.jsx(ae,{className:"mr-2 h-4 w-4 animate-spin"})," Criandoâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qr,{className:"mr-2 h-4 w-4"})," Criar protocolo"]})})]})]})}),e.jsx(Pt,{open:!!o,onOpenChange:s=>{s||(ts(null),Da(null))},children:e.jsx(zt,{children:o&&e.jsxs(e.Fragment,{children:[e.jsxs(At,{className:"mb-4",children:[e.jsx(Et,{children:"Detalhes do protocolo"}),e.jsx(Rt,{children:"Beneficiário, situação, documentos e ações disponÃveis."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border border-border/40 p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("code",{className:"text-sm font-semibold",children:o.protocol||"â"}),e.jsx(qs,{status:o.status})]}),e.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:[o.source," · ",Z(o.created_at,!0)]})]}),o.protocol&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.source_table==="appointments"&&!!((xt=ot.data)!=null&&xt.voucher_issued_at||(ht=ot.data)!=null&&ht.voucher_generated_at)&&e.jsx(g,{size:"sm",onClick:()=>jr(o.protocol),children:"Abrir autorização"}),e.jsx(g,{size:"sm",variant:"outline",onClick:()=>Ms(o.protocol),children:"Copiar protocolo"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(q,{label:"Cliente",value:o.subject_name}),e.jsx(q,{label:"CPF",value:o.subject_cpf?Je(o.subject_cpf):null}),e.jsx(q,{label:"E-mail",value:o.subject_email?le(o.subject_email):null}),e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(q,{label:"Telefone",value:rs===o.ref_id?o.subject_phone:ao(o.subject_phone),copyable:rs===o.ref_id,onCopy:Ms})}),o.subject_phone&&e.jsx(g,{type:"button",size:"sm",variant:"ghost",className:"shrink-0 px-2 text-xs",onClick:()=>Da(s=>s===o.ref_id?null:o.ref_id),"aria-label":rs===o.ref_id?"Ocultar telefone":"Mostrar telefone",children:rs===o.ref_id?"Ocultar":"Mostrar"})]}),o.reason_label&&e.jsx(q,{label:"Motivo",value:o.reason_label}),e.jsx(q,{label:"Atualizado em",value:Z(o.updated_at,!0)})]}),e.jsxs("details",{className:"rounded-lg border border-border/40 p-3 text-xs",children:[e.jsx("summary",{className:"cursor-pointer font-medium",children:"Detalhes técnicos"}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(q,{label:"Referência",value:o.ref_id,mono:!0,copyable:!0,onCopy:Ms}),e.jsx(q,{label:"Origem interna",value:o.source_table,mono:!0}),e.jsx(q,{label:"Chave de origem",value:o.source_key,mono:!0,copyable:!!o.source_key,onCopy:Ms}),o.origin_label&&e.jsx(q,{label:"Origem consolidada",value:o.origin_label})]})]}),o.source_table==="admin_manual_protocols"&&e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"rounded-lg border border-border/40 bg-muted/20 p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-semibold",children:"CRM"}),e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:((ft=w.data)==null?void 0:ft.bitrix_sync_status)==="synced"?"Sincronização concluÃda.":((jt=w.data)==null?void 0:jt.bitrix_sync_status)==="failed"?"Falha de sincronização; o protocolo local permanece válido e pode ser reenviado.":"Sincronização pendente."}),((gt=w.data)==null?void 0:gt.bitrix_sync_error)&&e.jsx("div",{className:"mt-1 text-[11px] text-destructive",children:String(w.data.bitrix_sync_error).slice(0,180)})]}),e.jsx(T,{variant:((bt=w.data)==null?void 0:bt.bitrix_sync_status)==="synced"?"default":"secondary",children:((vt=w.data)==null?void 0:vt.bitrix_sync_status)||"carregando"})]}),((yt=w.data)==null?void 0:yt.bitrix_sync_status)==="failed"&&e.jsx(g,{size:"sm",variant:"outline",className:"mt-3",onClick:fr,disabled:ma,children:ma?e.jsxs(e.Fragment,{children:[e.jsx(ae,{className:"mr-2 h-3.5 w-3.5 animate-spin"})," Sincronizandoâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"mr-2 h-3.5 w-3.5"})," Reenviar ao CRM"]})})]}),e.jsxs("div",{className:"rounded-lg border border-border/40 bg-muted/20 p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-semibold",children:"Notificação ao cliente"}),e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:((_t=w.data)==null?void 0:_t.notification_status)==="sent"?`Envio solicitado em ${Z(((Nt=w.data)==null?void 0:Nt.notification_sent_at)||null,!0)}`:((Ct=w.data)==null?void 0:Ct.notification_status)==="failed"?"Falha no envio; protocolo permanece válido.":((St=w.data)==null?void 0:St.notification_status)==="skipped_no_email"?"Não aplicável: cliente sem e-mail válido.":"Aguardando confirmação de envio."}),((wt=w.data)==null?void 0:wt.notification_error)&&e.jsx("div",{className:"mt-1 text-[11px] text-destructive",children:String(w.data.notification_error).slice(0,180)})]}),e.jsx(T,{variant:((kt=w.data)==null?void 0:kt.notification_status)==="sent"?"default":"secondary",children:((Mt=w.data)==null?void 0:Mt.notification_status)||"carregando"})]}),((Ft=w.data)==null?void 0:Ft.notification_status)==="failed"&&e.jsx(g,{size:"sm",variant:"outline",className:"mt-3",onClick:hr,disabled:ua,children:ua?e.jsxs(e.Fragment,{children:[e.jsx(ae,{className:"mr-2 h-3.5 w-3.5 animate-spin"}
12)," Enviandoâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"mr-2 h-3.5 w-3.5"})," Reenviar e-mail"]})})]})]}),o.protocol&&o.source_table!=="admin_manual_protocols"&&e.jsx(oo,{row:o}),e.jsx(Lt,{history:qe.data||[],loading:qe.isLoading,currentRefId:o.ref_id,onOpen:Xe})]})]})})}),e.jsx(Pt,{open:!!k,onOpenChange:s=>!s&&ue(null),children:e.jsx(zt,{children:k&&e.jsxs(e.Fragment,{children:[e.jsxs(At,{className:"mb-4",children:[e.jsx(Et,{children:k.display_name||"Beneficiário"}),e.jsxs(Rt,{children:[k.total_protocols," protocolo(s) · ",k.distinct_sources," canal(is) de atendimento."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(g,{size:"sm",onClick:()=>dr(k),disabled:Oe.isLoading,children:"Novo protocolo para este beneficiário"}),e.jsx(g,{size:"sm",variant:"outline",onClick:()=>{const s=k.display_cpf||k.display_email||k.display_name||"";ue(null),I(s),Ma("busca")},children:"Localizar protocolos"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:[e.jsx(q,{label:"CPF",value:qa(k.display_cpf)}),e.jsx(q,{label:"E-mail",value:k.display_email?le(k.display_email):null}),e.jsx(q,{label:"Telefone",value:k.display_phone}),e.jsx(q,{label:"Primeira interação",value:Z(k.first_interaction_at,!0)}),e.jsx(q,{label:"Ãltima interação",value:Z(k.last_interaction_at,!0)})]}),e.jsxs("details",{className:"rounded-lg border border-border/40 p-3 text-xs",children:[e.jsx("summary",{className:"cursor-pointer font-medium",children:"Detalhes técnicos"}),e.jsx("div",{className:"mt-3",children:e.jsx(q,{label:"Chave consolidada",value:k.client_key,mono:!0})})]}),e.jsx(Lt,{history:qe.data||[],loading:qe.isLoading,currentRefId:null,onOpen:s=>{ue(null),Xe(s)}})]})]})})})]})}function Ye({label:a,compact:i=!1}){return e.jsxs("div",{className:`flex items-center justify-center text-sm text-muted-foreground ${i?"py-6":"py-16"}`,children:[e.jsx(ae,{className:"mr-2 h-4 w-4 animate-spin text-primary"}),a]})}function zs({title:a,description:i,compact:d=!1}){return e.jsxs("div",{className:`text-center ${d?"py-6":"py-14"}`,children:[e.jsx("div",{className:"text-sm font-medium",children:a}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:i})]})}function Dt({page:a,setPage:i,totalPages:d,pageSize:u,setPageSize:p,total:j}){return e.jsx(Pr,{page:a+1,totalPages:d,totalItems:j,pageSize:u,pageSizeOptions:so,onPageChange:v=>i(Math.max(0,v-1)),onPageSizeChange:p})}function q({label:a,value:i,mono:d=!1,copyable:u=!1,onCopy:p}){return e.jsxs("div",{className:"min-w-0 rounded-md border border-border/40 p-2.5",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase tracking-wide text-muted-foreground",children:a}),e.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[e.jsx("div",{className:`min-w-0 flex-1 break-words text-xs ${d?"font-mono":""}`,children:i||"â"}),u&&i&&p&&e.jsx(g,{size:"icon",variant:"ghost",className:"h-6 w-6 shrink-0",onClick:()=>p(i),children:e.jsx(Ir,{className:"h-3 w-3"})})]})]})}function Lt({history:a,loading:i,currentRefId:d,onOpen:u}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(Ot,{className:"h-4 w-4"})," Histórico do beneficiário"]}),e.jsx(T,{variant:"outline",children:a.length})]}),i?e.jsx(Ye,{compact:!0,label:"Carregando históricoâ¦"}):a.length===0?e.jsx(zs,{compact:!0,title:"Sem histórico relacionado",description:"Não há outros protocolos vinculados a esta identidade."}):e.jsx("div",{className:"space-y-2",children:a.map(p=>e.jsx("div",{className:`rounded-lg border p-3 ${d===p.ref_id?"border-primary/30 bg-primary/5":"border-border/40"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>u(p),children:[e.jsx("div",{className:"truncate text-xs font-medium",children:p.source}),e.jsx("code",{className:"text-[11px] text-muted-foreground",children:p.protocol||"sem protocolo"}),e.jsx("div",{className:"mt-1 text-[10px] text-muted-foreground",children:Z(p.created_at,!0)})]}),e.jsx(qs,{status:p.status})]})},`${p.source_table}-${p.ref_id}-${p.protocol}`))})]})}function oo({row:a}){const i=ro(a.source_table),[d,u]=r.useState({kind:"checking"});r.useEffect(()=>{let j=!1;return u({kind:"checking"}),z.functions.invoke("admin-bitrix-map?action=check-protocol-spawn",{body:{protocol:a.protocol}}).then(({data:v,error:c})=>{var I,G;if(j)return;if(c){u({kind:"idle"});return}const l=v==null?void 0:v.success,N=((I=l==null?void 0:l.payload_summary)==null?void 0:I.entity)==="lead"?"lead":((G=l==null?void 0:l.payload_summary)==null?void 0:G.entity)==="deal"?"deal":i,U=l!=null&&l.target_deal_id?String(l.target_deal_id):"";
12v!=null&&v.sent&&U?u({kind:"sent",entity:N,entityId:U,url:Tt(N,U),deduped:!0}):u({kind:"idle"})}).catch(()=>{j||u({kind:"idle"})}),()=>{j=!0}},[a.protocol,a.ref_id,i]);const p=async()=>{u({kind:"loading"});try{const{data:j,error:v}=await z.functions.invoke("admin-bitrix-map?action=send-protocol",{body:{ref_id:a.ref_id,source_table:a.source_table,protocol:a.protocol,source_key:a.source_key,status:a.status,subject:{name:a.subject_name,cpf:a.subject_cpf,email:a.subject_email,phone:a.subject_phone}}});if(v)throw v;const c=j;if(!(c!=null&&c.ok))throw new Error((c==null?void 0:c.error)||"falha desconhecida");const l=c.entity==="lead"?"lead":c.entity==="deal"?"deal":i,N=String(l==="lead"?c.lead_id||c.deal_id||"":c.deal_id||c.lead_id||"");if(!N)throw new Error("CRM não retornou o ID da entidade criada");const I=(typeof c.entity_url=="string"&&c.entity_url.includes(`/crm/${l}/`)?c.entity_url:typeof c.deal_url=="string"&&c.deal_url.includes(`/crm/${l}/`)?c.deal_url:null)||Tt(l,N);u({kind:"sent",entity:l,entityId:N,url:I,deduped:!!c.deduped}),b.success(c.deduped?`Registro já existente no CRM â ${l==="lead"?"Lead":"Deal"} vinculado.`:`Enviado ao CRM como ${l==="lead"?"Lead":"Deal"}.`)}catch(j){const v=ve(j).slice(0,220)||"Falha ao enviar";u({kind:"error",message:v}),b.error(v)}};if(d.kind==="checking")return e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-border/40 px-3 py-2 text-xs text-muted-foreground",children:[e.jsx(ae,{className:"h-3 w-3 animate-spin"})," Verificando vÃnculo no CRMâ¦"]});if(d.kind==="sent"){const j=d.entity==="lead"?"Lead":"Deal";return e.jsxs("div",{className:"space-y-2 rounded-lg border border-emerald-500/30 bg-emerald-500/5 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-emerald-700 dark:text-emerald-400",children:[e.jsx(It,{className:"h-4 w-4"})," ",d.deduped?"Já vinculado ao CRM":"Enviado ao CRM"]}),e.jsx(g,{size:"sm",variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:d.url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Vr,{className:"mr-2 h-3.5 w-3.5"})," Abrir ",j," #",d.entityId]})})]})}return d.kind==="error"?e.jsxs("div",{className:"space-y-2 rounded-lg border border-destructive/30 bg-destructive/5 p-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-xs text-destructive",children:[e.jsx(Or,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("span",{children:d.message})]}),e.jsxs(g,{size:"sm",variant:"outline",className:"w-full",onClick:p,children:[e.jsx(es,{className:"mr-2 h-3.5 w-3.5"})," Tentar novamente"]})]}):e.jsxs("div",{className:"space-y-2 rounded-lg border border-border/40 p-3",children:[e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Envio manual ao CRM com proteção contra duplicidade."}),e.jsx(g,{size:"sm",className:"w-full",onClick:p,disabled:d.kind==="loading",children:d.kind==="loading"?e.jsxs(e.Fragment,{children:[e.jsx(ae,{className:"mr-2 h-3.5 w-3.5 animate-spin"})," Enviandoâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(Sr,{className:"mr-2 h-3.5 w-3.5"})," Enviar para CRM"]})})]})}export{li 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.