1import{r as e,j as s}from"./framer-DNXtdBgj.js";import{A as a}from"./AdminLayout-DLcnHFvP.js";import{L as r,I as l,B as o,e as n,bc as t}from"./index-XTUkK5WH.js";import{C as i,a as c,b as d,e as m,c as x}from"./card-Bfb46Kgw.js";import{L as h}from"./label-DF-Tz1WR.js";import{S as u}from"./switch-D8iy4Yst.js";import{B as j}from"./badge-5FdbKFYY.js";import{S as p,a as _,b as f,c as y,d as g}from"./select-DQMgvcBO.js";import{Z as v}from"./ZohoOAuthDialog-Da0QxH-m.js";import{R as N}from"./refresh-cw-BQas9oJM.js";import{F as b}from"./flask-conical-BlsHoGJc.js";import{S as k}from"./save-Buqk_0cO.js";import{P as w}from"./plus-BWMdkkfo.js";import"./users-round-C_OE1rsU.js";import"./file-text-IPr1Bv1X.js";import"./rocket-Ckmnaf0E.js";import"./wrench-k69Xhg9M.js";import"./factory-g-lDNgT_.js";import"./target-CQCdL--z.js";import"./package-BE07Fgma.js";import"./puzzle-ms8g5hLX.js";import"./building-2-Cf048s_3.js";import"./users-BomTj5bm.js";import"./chart-column-x2tYRpNA.js";import"./supabase-CVkO6afG.js";import"./index-jVOyRz7F.js";import"./chevron-up-Z5mg4Tbw.js";import"./textarea-x1LPr9Af.js";import"./dialog-CCYtSJ9h.js";import"./trash-2-CSXn37pz.js";import"./external-link-CHm8ztBE.js";import"./plug-DK6c2MQ-.js";import"./eye-DGqLm-TM.js";import"./copy-DvFQ8OQF.js";import"./circle-alert-n9Uv_QXA.js";const C="__round_robin__";function z(){const[z,S]=e.useState([]),[A,M]=e.useState([]),[R,Z]=e.useState({}),[L,$]=e.useState([]),[D,F]=e.useState(!0),[O,P]=e.useState(null),[V,I]=e.useState(null),[E,q]=e.useState(null),[B,T]=e.useState(""),[J,K]=e.useState(""),Q=async()=>{F(!0);try{const[e,s,a]=await Promise.all([n.from("zoho_routing_rules").select("*").order("source_key"),n.from("sales_reps").select("id, name, zoho_user_id, is_active").order("name"),n.functions.invoke("zoho-oauth-config",{body:{action:"list_connections"}})]);S(e.data||[]),M(s.data||[]),$(a.data?.connections||[])}catch(e){t.error(e.message||"Falha ao carregar regras")}finally{F(!1)}};e.useEffect(()=>{Q()},[]);const H=(e,s)=>{S(a=>a.map(a=>a.id===e?{...a,...s}:a))};return s.jsx(a,{children:s.jsxs("div",{className:"space-y-6 max-w-5xl",children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"font-display text-3xl font-bold",children:"Roteamento Zoho"}),s.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Configure, por origem (formulário, LP, diagnóstico, newsletter), para onde cada lead deve ir no Zoho â CRM, Marketing Automation ou ambos."})]}),s.jsx(v,{})]}),s.jsxs(i,{children:[s.jsxs(c,{className:"pb-3",children:[s.jsx(d,{className:"text-lg",children:"Conexões Zoho"}),s.jsx(m,{children:'Cada regra abaixo escolhe qual conexão usar para CRM e para Marketing Automation. Configure novas conexões pelo botão "Configurar Zoho OAuth" acima.'})]}),s.jsx(x,{className:"flex items-center gap-2 flex-wrap",children:0===L.length?s.jsx("span",{className:"text-xs text-muted-foreground",children:"Nenhuma conexão cadastrada."}):L.map(e=>s.jsxs(j,{variant:"outline",className:"font-mono text-[11px]",children:[e.label||e.connection_key,s.jsxs("span",{className:"ml-1 opacity-60",children:["(",e.product,")"]}),s.jsx("span",e.refresh_token_set?{className:"ml-1 text-emerald-600",children:"â"}:{className:"ml-1 text-amber-600",children:"â"})]},e.connection_key))})]}),D?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx(r,{className:"h-6 w-6 animate-spin text-primary"})}):s.jsxs("div",{className:"space-y-4",children:[z.map(e=>s.jsxs(i,{className:e.enabled?"":"opacity-70",children:[s.jsx(c,{className:"pb-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(d,{className:"text-lg",children:e.label}),s.jsx(j,{variant:"outline",className:"font-mono text-[11px]",children:e.source_key}),s.jsx(j,e.enabled?{className:"bg-emerald-100 text-emerald-800 hover:bg-emerald-100",children:"Ativa"}:{variant:"outline",children:"Desativada"})]}),e.notes&&s.jsx("p",{className:"text-xs text-muted-foreground",children:e.notes})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(h,{className:"text-xs text-muted-foreground",children:"Habilitar"}),s.jsx(u,{checked:e.enabled,onCheckedChange:s=>H(e.id,{enabled:s})})]})]})}),s.jsxs(x,{className:"space-y-5",children:[s.jsxs("div",{className:"rounded-md border p-4 space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium text-sm",children:"Zoho CRM (Lead)"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Cria um Lead no módulo CRM ao receber esse tipo de origem."})]}),s.jsx(u,{checked:e.crm_enabled,onCheckedChange:s=>H(e.id,{crm_enabled:s})})]}),e.crm_enabled&&s.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[s.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[s.jsx(h,{className:"text-xs",children:"Conexão Zoho (CRM)"}),s.jsxs(p,{value:e.crm_connection_key||"default",onValueChange:s=>H(e.id,{crm_connection_key:s}),children:[s.jsx(_,{children:s.jsx(f,{})}),s.jsx(y,{children:0===L.length?s.jsx(g,{value:"default",children:"default"}):L.map(e=>s.jsxs(g,{value:e.connection_key,children:[e.label||e.connection_key," (",e.product,")"]},e.connection_key))})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(h,{htmlFor:`ls-${e.id}`,className:"text-xs",children:"Lead Source"}),s.jsx(l,{id:`ls-${e.id}`,value:e.crm_lead_source||"",placeholder:"Ex: Site, Diagnóstico Oten",onChange:s=>H(e.id,{crm_lead_source:s.target.value})})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(h,{htmlFor:`lst-${e.id}`,className:"text-xs",children:"Lead Status de entrada"}),s.jsx(l,{id:`lst-${e.id}`,value:e.crm_lead_status||"",placeholder:"Ex: Not Contacted, Qualified",onChange:s=>H(e.id,{crm_lead_status:s.target.value})}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Deve corresponder exatamente a um valor configurado no Zoho CRM. Vazio = usa o default do Zoho."})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(h,{className:"text-xs",children:"Owner padrão"}),s.jsxs(p,{value:e.crm_owner_zoho_id||C,onValueChange:s=>H(e.id,{crm_owner_zoho_id:s===C?null:s}),children:[s.jsx(_,{children:s.jsx(f,{})}),s.jsxs(y,{children:[s.jsx(g,{value:C,children:"Round-robin (sales_reps)"}),A.filter(e=>e.zoho_user_id).map(e=>s.jsx(g,{value:e.zoho_user_id,children:e.name},e.id))]})]})]})]})]}),s.jsxs("div",{className:"rounded-md border p-4 space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium text-sm",children:"Zoho Marketing Automation"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Inscreve o email em uma mailing list (e opcionalmente uma journey)."})]}),s.jsx(u,{checked:e.ma_enabled,onCheckedChange:s=>H(e.id,{ma_enabled:s})})]}),e.ma_enabled&&s.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[s.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[s.jsx(h,{className:"text-xs",children:"Conexão Zoho (MA)"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(p,{value:e.ma_connection_key||"default",onValueChange:s=>H(e.id,{ma_connection_key:s}),children:[s.jsx(_,{className:"flex-1",children:s.jsx(f,{})}),s.jsx(y,{children:0===L.length?s.jsx(g,{value:"default",children:"default"}):L.map(e=>s.jsxs(g,{value:e.connection_key,children:[e.label||e.connection_key," (",e.product,")"]},e.connection_key))})]}),s.jsx(o,{variant:"outline",size:"sm",type:"button",onClick:()=>(async e=>{q(e);try{const{data:s,error:a}=await n.functions.invoke("zoho-oauth-config",{body:{action:"lists",connection_key:e}});if(a)throw a;const r=s?.lists||[];Z(s=>({...s,[e]:r})),t.success(`${r.length} lista(s) carregada(s) (${e})`)}catch(s){t.error(s.message||`Falha ao carregar listas para "${e}". Autorize a conexão primeiro.`)}finally{q(null)}})(e.ma_connection_key||"default"),disabled:E===(e.ma_connection_key||"default"),children:E===(e.ma_connection_key||"default")?
1s.jsx(r,{className:"h-4 w-4 animate-spin"}):s.jsx(N,{className:"h-4 w-4"})})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(h,{className:"text-xs",children:"Mailing List"}),(R[e.ma_connection_key||"default"]?.length??0)>0?s.jsxs(p,{value:e.ma_list_key||"",onValueChange:s=>H(e.id,{ma_list_key:s}),children:[s.jsx(_,{children:s.jsx(f,{placeholder:"Selecioneâ¦"})}),s.jsx(y,{children:(R[e.ma_connection_key||"default"]||[]).map(e=>s.jsx(g,{value:e.listkey,children:e.listname},e.listkey))})]}):s.jsx(l,{value:e.ma_list_key||"",placeholder:"listkey (clique no Ãcone para carregar listas)",onChange:s=>H(e.id,{ma_list_key:s.target.value})})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(h,{className:"text-xs",children:"Journey ID (opcional)"}),s.jsx(l,{value:e.ma_journey_id||"",placeholder:"ID da journey",onChange:s=>H(e.id,{ma_journey_id:s.target.value})})]})]})]}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsxs(o,{variant:"outline",size:"sm",onClick:()=>(async e=>{I(e.id);try{const{error:s}=await n.functions.invoke("zoho-sync-lead",{body:{source_key:e.source_key,email:`test+${Date.now()}@otentecnologia.com.br`,dry_run:!0}});if(s)throw s;t.success("Teste OK",{description:`Regra carregada: CRM=${e.crm_enabled?"â":"â"} MA=${e.ma_enabled?"â":"â"}`})}catch(s){t.error(s.message||"Falha no teste")}finally{I(null)}})(e),disabled:V===e.id,children:[V===e.id?s.jsx(r,{className:"h-4 w-4 mr-2 animate-spin"}):s.jsx(b,{className:"h-4 w-4 mr-2"}),"Testar (dry-run)"]}),s.jsxs(o,{size:"sm",onClick:()=>(async e=>{P(e.id);try{const{error:s}=await n.from("zoho_routing_rules").update({label:e.label,enabled:e.enabled,crm_enabled:e.crm_enabled,crm_lead_source:e.crm_lead_source,crm_owner_zoho_id:e.crm_owner_zoho_id,crm_lead_status:e.crm_lead_status,ma_enabled:e.ma_enabled,ma_list_key:e.ma_list_key,ma_journey_id:e.ma_journey_id,notes:e.notes,crm_connection_key:e.crm_connection_key||"default",ma_connection_key:e.ma_connection_key||"default"}).eq("id",e.id);if(s)throw s;t.success(`Regra "${e.label}" salva`)}catch(s){t.error(s.message||"Falha ao salvar")}finally{P(null)}})(e),disabled:O===e.id,children:[O===e.id?s.jsx(r,{className:"h-4 w-4 mr-2 animate-spin"}):s.jsx(k,{className:"h-4 w-4 mr-2"}),"Salvar"]})]})]})]},e.id)),s.jsxs(i,{children:[s.jsxs(c,{className:"pb-3",children:[s.jsx(d,{className:"text-base",children:"Adicionar nova origem"}),s.jsxs(m,{children:["Use para mapear LPs ou formulários especÃficos. O ",s.jsx("code",{children:"source_key"})," deve bater com o ",s.jsx("code",{children:"form_type"})," usado pelo formulário."]})]}),s.jsxs(x,{className:"flex flex-col sm:flex-row gap-2",children:[s.jsx(l,{placeholder:"source_key (ex: lp_implantacao_v2)",value:B,onChange:e=>T(e.target.value),className:"font-mono text-sm"}),s.jsx(l,{placeholder:"Nome amigável",value:J,onChange:e=>K(e.target.value)}),s.jsxs(o,{onClick:async()=>{if(B.trim()&&J.trim())try{const{error:e}=await n.from("zoho_routing_rules").insert({source_key:B.trim(),label:J.trim()});if(e)throw e;t.success("Origem adicionada"),T(""),K(""),await Q()}catch(e){t.error(e.message||"Falha ao criar")}else t.warning("Preencha source_key e label")},variant:"outline",children:[s.jsx(w,{className:"h-4 w-4 mr-2"}),"Adicionar"]})]})]})]})]})})}export{z 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.