1import{c as ve,r as c,s as p,j as t,J as Ne,ah as ne,ai as re,aj as ie,ak as le,al as M,B as S,N as oe,d as w,n as f,o as ye,a9 as h}from"./index-B9VPSq2u.js";import{T as Se}from"./textarea-CVfEVFXV.js";import{u as Ce}from"./useTeamPhoneDirectory-7W9cUBFw.js";import{S as ze}from"./search-BGWf2lmH.js";import{U as D}from"./user-DA3dd-GG.js";import{P as $e}from"./phone-DBJux0eq.js";import{M as ke}from"./message-square-Tv4fTDhx.js";import{S as Ee}from"./send-DEa1uq5N.js";/** 2 * @license lucide-react v0.462.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const Me=ve("CloudDownload",[["path",{d:"M12 13v8l-4-4",key:"1f5nwf"}],["path",{d:"m12 21 4-4",key:"1lfcce"}],["path",{d:"M4.393 15.269A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.436 8.284",key:"ui1hmy"}]]);function Pe({refreshKey:de}){var U,J,G,H,Q,X,Y;const[x,ce]=c.useState([]),{matchAny:j}=Ce(),[d,me]=c.useState(null),[C,ue]=c.useState([]),[T,pe]=c.useState([]),[_,I]=c.useState(""),[b,L]=c.useState(""),[xe,R]=c.useState(!1),[v,fe]=c.useState(""),[he,z]=c.useState(!0),[$,_e]=c.useState("all"),[B,q]=c.useState(!1),F=c.useRef(null),k=c.useRef(null);c.useEffect(()=>{g(),ge()},[de]),c.useEffect(()=>(k.current=setInterval(()=>{g(),d&&E(d)},8e3),()=>{k.current&&clearInterval(k.current)}),[d]),c.useEffect(()=>{d&&E(d)},[d]),c.useEffect(()=>{var e;(e=F.current)==null||e.scrollIntoView({behavior:"smooth"})},[C]);const g=async()=>{var te,se;z(!0);const{data:e,error:s}=await p.from("whatsapp_inbox").select("phone_normalized, phone, message_text, created_at, direction, lead_id, intent_detected, instance_name, is_group").order("created_at",{ascending:!1}).limit(1e3);if(s){console.error("Error loading inbox:",s),z(!1);return}const n=new Map;for(const a of e||[]){const r=a.phone_normalized||a.phone;n.has(r)||n.set(r,{phone_normalized:r,phone_raw:a.phone,last_message:a.message_text||`[${a.direction}]`,last_at:a.created_at,lead_name:null,lead_id:a.lead_id,intent:a.intent_detected,unread_count:0,instance_name:a.instance_name??null,is_group:!!a.is_group,funil:null,vendedor:null,treinamento:null})}const o=[...n.values()],m=[...new Set(o.filter(a=>!a.is_group).map(a=>a.phone_normalized||a.phone_raw).filter(Boolean))],i=new Map;if(m.length>0){const{data:a,error:r}=await p.rpc("fn_resolve_wa_inbox_leads",{p_keys:m});r&&console.error("Erro no match de leads:",r);for(const u of a??[])i.set(u.conv_key,u)}const y=[...new Set([...o.filter(a=>a.lead_id).map(a=>a.lead_id),...[...i.values()].map(a=>a.lead_id)])],Z=new Map;if(y.length>0){const{data:a}=await p.from("lia_attendances").select("id, nome, piperun_pipeline_name, funil_entrada_crm, piperun_stage_name, proprietario_lead_crm, cs_treinamento, data_treinamento").in("id",y.slice(0,500));for(const r of a??[])Z.set(r.id,r)}for(const a of o){const r=i.get(a.phone_normalized)||i.get(a.phone_raw),u=a.lead_id||(r==null?void 0:r.lead_id)||null;if(!u)continue;const l=Z.get(u);a.lead_id=u,a.lead_name=(l==null?void 0:l.nome)||(r==null?void 0:r.nome)||a.lead_name,a.funil=(l==null?void 0:l.piperun_pipeline_name)||(l==null?void 0:l.funil_entrada_crm)||(r==null?void 0:r.funil)||null,a.vendedor=(l==null?void 0:l.proprietario_lead_crm)||(r==null?void 0:r.vendedor)||null,a.treinamento=l!=null&&l.cs_treinamento?`${l.cs_treinamento}${l.data_treinamento?` ⢠${new Date(l.data_treinamento).toLocaleDateString("pt-BR")}`:""}`:null}const ee=[...new Set(o.filter(a=>a.lead_id).map(a=>a.lead_id))];if(ee.length>0){const{data:a}=await p.from("smartops_course_enrollments").select("lead_id, status, turma_snapshot, enrolled_at").in("lead_id",ee).order("enrolled_at",{ascending:!1});if(a){const r=new Map;for(const u of a)u.lead_id&&!r.has(u.lead_id)&&r.set(u.lead_id,u);for(const u of o){if(!u.lead_id)continue;const l=r.get(u.lead_id);if(!l)continue;const ae=((te=l.turma_snapshot)==null?void 0:te.course_name)||((se=l.turma_snapshot)==null?void 0:se.curso)||"";u.treinamento=`${l.status||"matriculado"}${ae?` ⢠${ae}`:""}`}}}ce(o),z(!1)},E=async e=>{const{data:s,error:n}=await p.from("whatsapp_inbox").select("*").or(`phone_normalized.eq.${e},phone.eq.${e}`).order("created_at",{ascending:!0}).limit(200);
6if(n){console.error("Error loading messages:",n);return}ue(s||[])},ge=async()=>{const{data:e}=await p.from("team_members").select("id, nome_completo, whatsapp_number, evolution_instance_name").eq("ativo",!0).not("evolution_instance_name","is",null);e&&(pe(e),e.length>0&&I(e[0].id))},we=async()=>{q(!0);try{const{data:e,error:s}=await p.functions.invoke("smart-ops-wa-capture-conversations",{body:{since_hours:168,pages:5,page_size:200}});if(s)throw s;const n=(e==null?void 0:e.results)??[],o=n.reduce((i,y)=>i+(y.inserted||0),0),m=n.filter(i=>i.error);h.success(`${o} mensagens capturadas de ${n.length} instância(s)`),m.length&&h.warning(`Instâncias com erro: ${m.map(i=>i.instance).join(", ")}`),g()}catch(e){h.error(`Erro ao sincronizar: ${e instanceof Error?e.message:String(e)}`)}finally{q(!1)}},[P,A]=c.useState(!1),je=async()=>{A(!0);try{const{data:e,error:s}=await p.rpc("fn_backfill_wa_inbox_lead_ids",{p_limit:5e3});if(s)throw s;const n=Array.isArray(e)?e[0]:e,{data:o,error:m}=await p.functions.invoke("smart-ops-wa-resolve-lid",{body:{dry_run:!1,limit:5e3,enable_name_match:!1}});if(m)throw m;const i=o;h.success(`${Number((n==null?void 0:n.updated_rows)??0)+Number((i==null?void 0:i.updated_rows)??0)} mensagens vinculadas a leads (${(n==null?void 0:n.matched_conversations)??0} conversas identificadas)`),g()}catch(e){h.error(`Erro ao resolver identidades: ${e instanceof Error?e.message:String(e)}`)}finally{A(!1)}},V=async()=>{if(!(!b.trim()||!d||!_)){R(!0);try{const e=x.find(o=>o.phone_normalized===d),{data:s,error:n}=await p.functions.invoke("smart-ops-wa-send",{body:{team_member_id:_,phone:(e==null?void 0:e.phone_raw)||d,tipo:"text",message:b,lead_id:(e==null?void 0:e.lead_id)||null}});if(n){let o=n.message;const m=n==null?void 0:n.context;if(m&&typeof m.json=="function"){const i=await m.json().catch(()=>null);i!=null&&i.detail?o=i.detail:i!=null&&i.error&&(o=i.error)}throw new Error(o)}if(s&&s.success===!1)throw new Error(s.detail||s.error);h.success("Mensagem enviada"),L(""),setTimeout(()=>E(d),1e3)}catch(e){h.error(`Erro ao enviar: ${e instanceof Error?e.message:String(e)}`)}finally{R(!1)}}},be=[...new Set(x.map(e=>e.instance_name).filter(Boolean))],K=x.filter(e=>{if($!=="all"&&e.instance_name!==$)return!1;if(!v)return!0;const s=v.toLowerCase().replace(/\D/g,""),n=v.toLowerCase(),o=j(e.phone_raw,e.phone_normalized);if(o&&o.nome_completo.toLowerCase().includes(n)||e.lead_name&&e.lead_name.toLowerCase().includes(n)||e.last_message&&e.last_message.toLowerCase().includes(n)||e.vendedor&&e.vendedor.toLowerCase().includes(n)||e.funil&&e.funil.toLowerCase().includes(n)||!s)return!0;const m=(e.phone_raw||e.phone_normalized||"").replace(/\D/g,"");return!!(m.includes(s)||s.length>=8&&m.endsWith(s))}),W=e=>{const s=new Date(e),o=new Date().getTime()-s.getTime();return o<864e5?s.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):o<6048e5?s.toLocaleDateString("pt-BR",{weekday:"short",hour:"2-digit",minute:"2-digit"}):s.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})},O=e=>e?e.includes("interesse")?"bg-green-100 text-green-800 border-green-200":e.includes("suporte")?"bg-yellow-100 text-yellow-800 border-yellow-200":e.includes("sem_interesse")?"bg-red-100 text-red-800 border-red-200":"bg-muted text-muted-foreground":"",N=e=>{const s=e.replace(/\D/g,"");return s.length===13?`+${s.slice(0,2)} (${s.slice(2,4)}) ${s.slice(4,9)}-${s.slice(9)}`:s.length===11?`(${s.slice(0,2)}) ${s.slice(2,7)}-${s.slice(7)}`:e};return t.jsxs("div",{className:"flex h-[calc(100vh-280px)] min-h-[500px] border rounded-lg bg-card overflow-hidden",children:[t.jsxs("div",{className:"w-80 border-r flex flex-col",children:[t.jsxs("div",{className:"p-3 border-b",children:[t.jsxs("div",{className:"relative",children:[t.jsx(ze,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),t.jsx(Ne,{placeholder:"Buscar nome ou telefone...",value:v,onChange:e=>fe(e.target.value),className:"pl-9"})]}),t.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[t.jsxs(ne,{value:$,onValueChange:_e,children:[t.jsx(re,{className:"h-8 text-xs flex-1",children:t.jsx(ie,{placeholder:"Todas as instâncias"})}),t.jsxs(le,{children:[t.jsx(M,{value:"all",children:"Todas as instâncias"}),be.map(e=>t.jsx(M,{value:e,children:e},e))]})]}),t.jsx(S,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:we,disabled:B,title:"Capturar c
6onversas de todas as instâncias (vendedor, CS e suporte)",children:B?t.jsx(oe,{className:"w-3.5 h-3.5 animate-spin"}):t.jsx(Me,{className:"w-3.5 h-3.5"})})]})]}),t.jsx("div",{className:"flex-1 overflow-y-auto",children:he?t.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"Carregando..."}):K.length===0?t.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"Nenhuma conversa encontrada"}):K.map(e=>{const s=j(e.phone_raw,e.phone_normalized);return t.jsxs("button",{onClick:()=>me(e.phone_normalized),className:w("w-full text-left p-3 border-b hover:bg-accent/50 transition-colors",d===e.phone_normalized&&"bg-accent"),children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("span",{className:"font-medium text-sm truncate flex items-center gap-1.5",children:s?t.jsxs(t.Fragment,{children:[t.jsx(D,{className:"w-3.5 h-3.5 text-emerald-600 shrink-0"}),s.nome_completo]}):e.lead_name?t.jsxs(t.Fragment,{children:[t.jsx(D,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0"}),e.lead_name]}):t.jsxs(t.Fragment,{children:[t.jsx($e,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0"}),N(e.phone_raw)]})}),t.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap ml-2",children:W(e.last_at)})]}),s&&t.jsx("div",{className:"mb-1",children:t.jsxs(f,{variant:"outline",className:"text-[9px] px-1.5 py-0 border-emerald-300 text-emerald-700 bg-emerald-50",children:["ð§âð¼ Equipe",s.role?` ⢠${s.role}`:"",s.ativo?"":" ⢠inativo"]})}),(s||e.lead_name)&&t.jsxs("p",{className:"text-[10px] text-muted-foreground mb-0.5",children:["ð± ",N(e.phone_raw)]}),!s&&(e.funil||e.vendedor||e.treinamento)&&t.jsxs("div",{className:"flex flex-wrap gap-1 mb-1",children:[e.funil&&t.jsxs(f,{variant:"outline",className:"text-[9px] px-1.5 py-0 border-blue-300 text-blue-700 bg-blue-50",children:["ð¯ ",e.funil]}),e.vendedor&&t.jsxs(f,{variant:"outline",className:"text-[9px] px-1.5 py-0 border-purple-300 text-purple-700 bg-purple-50",children:["ð¤ ",e.vendedor]}),e.treinamento&&t.jsxs(f,{variant:"outline",className:"text-[9px] px-1.5 py-0 border-amber-300 text-amber-700 bg-amber-50",children:["ð ",e.treinamento]})]}),t.jsx("p",{className:"text-xs text-muted-foreground truncate",children:e.last_message}),e.instance_name&&t.jsxs(f,{variant:"secondary",className:"mt-1 mr-1 text-[9px] px-1.5 py-0",children:[e.instance_name,e.is_group?" ⢠grupo":""]}),e.intent&&t.jsx(f,{variant:"outline",className:w("mt-1 text-[10px] px-1.5 py-0",O(e.intent)),children:e.intent})]},e.phone_normalized)})}),t.jsxs("div",{className:"p-2 border-t text-xs text-muted-foreground text-center flex items-center justify-center gap-2",children:[t.jsxs("span",{children:[x.length," conversas"]}),t.jsx(S,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>g(),children:t.jsx(ye,{className:"w-3 h-3"})}),t.jsxs(S,{variant:"ghost",size:"sm",className:"h-6 px-2 text-[10px]",onClick:je,disabled:P,title:"Resolver identidades (LID â lead)",children:[P?t.jsx(oe,{className:"w-3 h-3 animate-spin"}):t.jsx(D,{className:"w-3 h-3"}),t.jsx("span",{className:"ml-1",children:"Resolver identidades"})]})]})]}),t.jsx("div",{className:"flex-1 flex flex-col",children:d?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"p-3 border-b flex items-center justify-between bg-muted/30",children:[t.jsxs("div",{children:[t.jsx("p",{className:"font-medium text-sm",children:((J=j((U=x.find(e=>e.phone_normalized===d))==null?void 0:U.phone_raw,d))==null?void 0:J.nome_completo)||((G=x.find(e=>e.phone_normalized===d))==null?void 0:G.lead_name)||N(((H=x.find(e=>e.phone_normalized===d))==null?void 0:H.phone_raw)||d)}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:["ð± ",N(((Q=x.find(e=>e.phone_normalized===d))==null?void 0:Q.phone_raw)||d)]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j((X=x.find(e=>e.phone_normalized===d))==null?void 0:X.phone_raw,d)&&t.jsx(f,{variant:"outline",className:"text-xs border-emerald-300 text-emerald-700 bg-emerald-50",children:"ð§âð¼ Membro da equipe"}),t.jsxs(f,{variant:"outline",className:"text-xs",children:[C.length," msgs"]})]})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3",children:[C.map(e=>{var s;return t.jsxs("div",{className:w("max-w-[75%] rounded-lg px-3 py-2 text-sm",e.direction==="inbound"?"bg-muted mr-auto":"bg-primary text-primary-foreground ml-auto"),children:[e.media_url&&t.jsx("div",{className:"mb-1",children:(s=e.media_type)!=null&&s.startsWith("image")?t.jsx("img",{src:e.media_url,alt:"media",className:"max-w-full rounded max-h-48"}):t.jsxs("a",{href:e.media_url,target:"_blank",rel:"noreferrer",className:"underline text-xs",children:["ð ",e.media_type||"arquivo"]})}),e.message_text&&t.jsx("p",{className:"whitespace-pre-wrap",children:e.message_text}),t.jsxs("div",{className:w("flex items-center gap-2 mt-1",e.direction==="inbound"?"justify-start":"justify-end"),children:[t.jsx("span",{className:"text-[10px] opacity-70",children:W(e.created_at)}),e.intent_detected&&e.direction==="inbound"&&t.jsx(f,{variant:"outline",className:w("text-[9px] px-1 py-0",O(e.intent_detected)),children:e.intent_detected})]})]},e.id)}),t.jsx("div",{ref:F})]}),t.jsxs("div",{className:"p-3 border-t space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs(ne,{value:_,onValueChange:I,children:[t.jsx(re,{className:"w-48",children:t.jsx(ie,{placeholder:"Selecionar remetente"})}),t.jsx(le,{children:T.map(e=>t.jsx(M,{value:e.id,children:e.nome_completo},e.id))})]}),t.jsx("span",{className:"text-xs text-muted-foreground",children:((Y=T.find(e=>e.id===_))==null?void 0:Y.whatsapp_number)||""})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(Se,{placeholder:"Digite sua mensagem...",value:b,onChange:e=>
6L(e.target.value),className:"min-h-[60px] max-h-[120px] resize-none",onKeyDown:e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),V())}}),t.jsx(S,{onClick:V,disabled:xe||!b.trim()||!_,className:"self-end",children:t.jsx(Ee,{className:"w-4 h-4"})})]})]})]}):t.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:t.jsxs("div",{className:"text-center",children:[t.jsx(ke,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),t.jsx("p",{className:"text-sm",children:"Selecione uma conversa para visualizar"})]})})})]})}export{Pe as SmartOpsWhatsAppInbox};
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.