PageSourceSearch

https://carregamento3bs.lovable.app/assets/ClientesPage-Du7zxzs9.js

js carregamento3bs.lovable.app collected 2026-10-03 05:35:35 UTC 17,257 bytes, 3 lines download raw bytes

1import{r as o,j as e,u as fe}from"./react-vendor-BorBU4Bs.js";import{b as re,aC as ve,B as u,P as ie,N as le,O as ce,Q as L,U as r,V as de,W as c,az as Ne,b0 as we,b1 as ye,T as ue,b2 as me,L as x,I as C,ae as be,s as d,u as Ce,a as Se,a$ as _e,A as Ee,D as ke,i as Ae,j as Te,k as qe,ax as Fe,b3 as Le,b4 as ze}from"./index-DkhxOMdR.js";import{C as De}from"./checkbox-Dl2yzLyD.js";import{u as xe,a as pe,b as O}from"./query-vendor-dlntIC_S.js";import{S as ee}from"./switch-FKqIeruD.js";import{u as Ie,T as ae}from"./TableColumnFilter-BcDRj-SX.js";import{u as Pe,S as oe}from"./SortableTableHead-BQcfj6gO.js";import{A as Re}from"./AuditHistoryDialog-DmwCV0IY.js";import{c as Ue}from"./cadastroAtivo-CMP99Sfl.js";import{P as he}from"./pencil-Cf5Ul2CU.js";import"./radix-vendor-CazrR58L.js";import"./charts-vendor-BxJanGhU.js";import"./supabase-vendor-BxTHC7hl.js";import"./xlsx-vendor-DOnNs5_d.js";import"./qr-vendor-Ca1-Dxvv.js";import"./arrow-up-wTT2lxSL.js";const ne={inicio:"Início",pronto:"Pronto",finalizado:"Finalizado"},Qe=["inicio","pronto","finalizado"];function Ke({clienteId:j}){const{toast:h}=re(),R=xe(),{data:$=[],isLoading:z}=pe({queryKey:["wa-contatos",j],queryFn:async()=>{const{data:s,error:a}=await d.from("clientes_whatsapp_contatos").select("*").eq("cliente_id",j).order("created_at",{ascending:!0});if(a)throw a;return s||[]}}),[i,U]=o.useState(null),[m,f]=o.useState("individual"),[S,_]=o.useState(""),[D,E]=o.useState(""),[k,A]=o.useState(""),[I,T]=o.useState(""),[v,N]=o.useState(["inicio","pronto","finalizado"]),[B,w]=o.useState(!0),[Q,q]=o.useState(!1),P=()=>{U(null),f("individual"),_(""),E(""),A(""),T(""),N(["inicio","pronto","finalizado"]),w(!0),q(!1)},F=()=>{P(),q(!0)},K=s=>{U(s.id),f(s.tipo==="grupo"?"grupo":"individual"),_(s.nome||""),E(s.tipo==="grupo"?"":s.telefone||""),A(s.grupo_nome||""),T(s.tipo==="grupo"&&s.telefone||""),N(s.eventos||[]),w(s.ativo!==!1),q(!0)},Y=s=>{N(a=>a.includes(s)?a.filter(y=>y!==s):[...a,s])},M=O({mutationFn:async()=>{if(!S.trim())throw new Error("Informe um nome");const s={cliente_id:j,nome:S.trim(),tipo:m,eventos:v,ativo:B};if(m==="individual"){const a=D.replace(/\D/g,"");if(!a)throw new Error("Informe o telefone");s.telefone=a,s.grupo_nome=null}else{if(!k.trim())throw new Error("Informe o nome do grupo");s.grupo_nome=k.trim(),s.telefone=I.trim()||null}if(i){const{error:a}=await d.from("clientes_whatsapp_contatos").update(s).eq("id",i);if(a)throw a}else{const{error:a}=await d.from("clientes_whatsapp_contatos").insert(s);if(a)throw a}},onSuccess:()=>{R.invalidateQueries({queryKey:["wa-contatos",j]}),P(),h({title:i?"Atualizado!":"Cadastrado!"})},onError:s=>h({title:"Erro",description:s.message,variant:"destructive"})}),W=O({mutationFn:async s=>{const{error:a}=await d.from("clientes_whatsapp_contatos").delete().eq("id",s);if(a)throw a},onSuccess:()=>{R.invalidateQueries({queryKey:["wa-contatos",j]}),h({title:"Removido"})},onError:s=>h({title:"Erro",description:s.message,variant:"destructive"})}),G=async(s,a)=>{const{error:y}=await d.from("clientes_whatsapp_contatos").update({ativo:a}).eq("id",s);if(y){h({title:"Erro",description:y.message,variant:"destructive"});return}R.invalidateQueries({queryKey:["wa-contatos",j]})},[J,H]=o.useState(null),V=async s=>{H(s.id);try{const a=s.tipo==="grupo"&&s.grupo_nome||s.nome,b={test_message:`✅ Teste de notificação 3BS
2
3Olá ${a}! Este é um envio de teste do sistema. Se você recebeu, o cadastro está funcionando corretamente.`};if(s.tipo==="grupo"){const g=(s.telefone||"").trim();if(g)b.test_group_jid=g;else if((s.grupo_nome||"").trim())b.test_group_name=s.grupo_nome.trim();else throw new Error("Cadastre o JID ou o nome do grupo")}else{const g=(s.telefone||"").replace(/\D/g,"");if(!g)throw new Error("Telefone inválido");b.test_phone=g}const{data:p,error:X}=await d.functions.invoke("whatsapp-notify",{body:b});if(X)throw X;if(p!=null&&p.error)throw new Error(p.error);if((p==null?void 0:p.ok)===!1)throw new Error(p.error||"Falha no envio");h({title:"Teste enviado",description:`Mensagem enviada para ${a}`})}catch(a){h({title:"Falha no envio",description:a.message||String(a),variant:"destructive"})}finally{H(null)}};return e.jsxs("div",{className:"border rounded-lg p-3 space-y-3 bg-muted/20",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-emerald-600",children:[e.jsx(ve,{className:"h-4 w-4"})," Contatos e grupos do WhatsApp"]}),!Q&&e.jsxs(u,{type:"button",size:"sm",variant:"outline",onClick:F,children:[e.jsx(ie,{className:"h-4 w-4 mr-1"})," Adicionar"]})]}),z?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Carregando..."}):$.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nenhum contato cadastrado."}):e.jsx("div",{className:"rounded border bg-card",children:e.jsxs(le,{children:[e.jsx(ce,{children:e.jsxs(L,{className:"table-header",children:[e.jsx(r,{className:"w-[90px]",children:"Tipo"}),e.jsx(r,{children:"Nome"}),e.jsx(r,{children:"Telefone / JID"}),e.jsx(r,{children:"Eventos"}),e.jsx(r,{className:"w-16 text-center",children:"Ativo"}),e.jsx(r,{className:"w-20 text-center",children:"Ações"})]})}),e.jsx(de,{children:$.map(s=>e.jsxs(L,{className:s.ativo===!1?"opacity-50":void 0,children:[e.jsx(c,{className:"text-xs",children:s.tipo==="grupo"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-indigo-500/10 text-indigo-600 dark:text-indigo-400",children:[e.jsx(Ne,{className:"h-3 w-3"})," Grupo"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:[e.jsx(we,{className:"h-3 w-3"})," Ind."]})}),e.jsx(c,{className:"font-medium text-sm",children:s.tipo==="grupo"&&s.grupo_nome||s.nome}),e.jsx(c,{className:"font-mono text-xs",children:s.telefone||"—"}),e.jsx(c,{className:"text-xs",children:(s.eventos||[]).map(a=>e.jsx("span",{className:"inline-block mr-1 px-1.5 py-0.5 rounded bg-primary/10 text-primary text-[10px]",children:ne[a]},a))}),e.jsx(c,{className:"text-center",children:e.jsx(ee,{checked:s.ativo!==!1,onCheckedChange:a=>G(s.id,a)})}),e.jsx(c,{children:e.jsxs("div",{className:"flex gap-0.5 justify-center",children:[e.jsx(u,{type:"button",variant:"ghost",size:"icon",title:"Enviar teste",onClick:()=>V(s),disabled:J===s.id||s.ativo===!1,children:e.jsx(ye,{className:`h-3.5 w-3.5 ${J===s.id?"opacity-50":"text-emerald-600"}`})}),e.jsx(u,{type:"button",variant:"ghost",size:"icon",onClick:()=>K(s),children:e.jsx(he,{className:"h-3.5 w-3.5"})}),e.jsx(u,{type:"button",variant:"ghost",size:"icon",onClick:()=>{confirm("Remover?")&&W.mutate(s.id)},children:e.jsx(ue,{className:"h-3.5 w-3.5 text-destructive"})})]})})]},s.id))})]})}),Q&&e.jsxs("div",{className:"border rounded p-3 space-y-3 bg-card",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-medium",children:[i?"Editar":"Novo"," destinatário"]}),e.jsx(u,{type:"button",variant:"ghost",size:"icon",onClick:P,children:e.jsx(me,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer text-sm",children:[e.jsx("input",{type:"radio",checked:m==="individual",onChange:()=>f("individual")})," Individual"]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer text-sm",children:[e.jsx("input",{type:"radio",checked:m==="grupo",onChange:()=>f("grupo")}
3)," Grupo"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(x,{className:"text-xs",children:"Nome"}),e.jsx(C,{value:S,onChange:s=>_(s.target.value),placeholder:m==="grupo"?"Ex: Contato do grupo":"Nome do responsável"})]}),m==="individual"?e.jsxs("div",{className:"space-y-1",children:[e.jsx(x,{className:"text-xs",children:"Telefone (DDD)"}),e.jsx(C,{value:D,onChange:s=>E(s.target.value),placeholder:"67999998888",inputMode:"numeric"})]}):e.jsxs("div",{className:"space-y-1",children:[e.jsx(x,{className:"text-xs",children:"Nome do grupo"}),e.jsx(C,{value:k,onChange:s=>A(s.target.value),placeholder:"Ex: 3BS · Cliente X"})]})]}),m==="grupo"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(x,{className:"text-xs",children:"JID do grupo (opcional, recomendado)"}),e.jsx(C,{value:I,onChange:s=>T(s.target.value),placeholder:"[email protected]",className:"font-mono text-xs"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Cole o JID capturado em Contatos WhatsApp → JIDs capturados."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(x,{className:"text-xs",children:"Eventos"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Qe.map(s=>e.jsxs("button",{type:"button",onClick:()=>Y(s),className:`text-xs px-2 py-1 rounded border ${v.includes(s)?"bg-primary text-primary-foreground border-primary":"bg-muted text-muted-foreground border-transparent"}`,children:[v.includes(s)&&e.jsx(be,{className:"h-3 w-3 inline mr-1"}),ne[s]]},s))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[e.jsx(ee,{checked:B,onCheckedChange:w})," Ativo"]}),e.jsx(u,{type:"button",size:"sm",onClick:()=>M.mutate(),disabled:M.isPending,children:M.isPending?"Salvando...":i?"Atualizar":"Adicionar"})]})]})]})}function os(){const j=fe(),{isAutoRefreshEnabled:h}=Ce(),{isMaster:R}=Se(),[$,z]=o.useState(!1),[i,U]=o.useState(null),[m,f]=o.useState(""),[S,_]=o.useState(""),[D,E]=o.useState(""),[k,A]=o.useState(!1),[I,T]=o.useState(1),[v,N]=o.useState(null),[B,w]=o.useState(null),[Q,q]=o.useState(null),P=o.useRef(null),{toast:F}=re(),K=xe(),{data:Y=[],isLoading:M}=pe({queryKey:["clientes"],queryFn:async()=>{const{data:t,error:n}=await d.from("clientes").select("*").order("nome");if(n)throw n;return t},refetchOnWindowFocus:h("clientes")}),W=o.useMemo(()=>({codigo:t=>t.codigo||"",nome:t=>t.nome||""}),[]),{filters:G,setFilter:J,filtered:H}=Ie(Y,W),{sort:V,toggleSort:s,sorted:a}=Pe(H,W),y=async(t,n)=>{const l=n.name.split(".").pop(),se=`${t}/logo.${l}`,{error:te}=await d.storage.from("client-logos").upload(se,n,{upsert:!0});if(te)throw te;return await ze("client-logos",se)},b=O({mutationFn:async()=>{let t=Q;if(i){v&&(t=await y(i,v));const{error:n}=await d.from("clientes").update({nome:m,codigo:S,cnpj:D||null,logo_url:t,triangulacao_fiscal:k,qtd_amostras_racao:I}).eq("id",i);if(n)throw n}else{const{data:n,error:l}=await d.from("clientes").insert({nome:m,codigo:S,cnpj:D||null,triangulacao_fiscal:k,qtd_amostras_racao:I}).select("id").single();if(l)throw l;v&&n&&(t=await y(n.id,v),await d.from("clientes").update({logo_url:t}).eq("id",n.id))}},onSuccess:()=>{K.invalidateQueries({queryKey:["clientes"]}),g(),F({title:i?"Atualizado!":"Cadastrado!"})},onError:t=>F({title:"Erro",description:t.message,variant:"destructive"})}),p=O({mutationFn:async t=>{if(await Ue("cliente",t)>0)throw new Error("Não é possível excluir: cliente possui movimentações (pedidos, estoque, rações ou carregamentos). Desative o cadastro.");const{error:l}=await d.from("clientes").delete().eq("id",t);if(l)throw l},onSuccess:()=>{K.invalidateQueries({queryKey:["clientes"]}),F({title:"Removido!"})},onError:t=>F({title:"Erro",description:t.message,variant:"destructive"})}),X=O({mutationFn:async({id:t,ativo:n})=>{const{error:l}=await d.from("clientes").update({ativo:n}).eq("id",t);if(l)throw l},onSuccess:()=>{K.invalidateQueries({queryKey:["clientes"]})},onError:t=>F({title:"Erro",description:t.message,variant:"destructive"})}),g=()=>{z(!1),U(null),f(""),_(""),E(""),A(!1),T(1),N(null),w(null),q(null)},ge=t=>{var l;const n=(l=t.target.files)==null?void 0:l[0];n&&(N(n),w(URL.createObjectURL(n)))},je=t=>{U(t.id),f(t.nome),_(t.codigo||""),E(t.cnpj||""),A(t.triangulacao_fiscal||!1),T(typeof t.qtd_amostras_racao=="number"?t.qtd_amostras_racao:1),q(t.logo_url||null),N(null),w(null),z(!0)},Z=B||Q;return e.jsxs("div",{className:"animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col items-center text-center gap-2 mb-6",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-xl bg-primary/20 text-primary",children:e.jsx(_e,{className:"h-6 w-6"})}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Clientes"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Gerencie os clientes cadastrados"})]}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs(u,{variant:"ghost",size:"sm",className:"-ml-2",onClick:()=>j("/cadastro"),children:[e.jsx(Ee,{className:"h-4 w-4 mr-1"})," Voltar ao menu"]}),e.jsxs(u,{onClick:()=>{g(),z(!0)},children:[e.jsx(ie,{className:"h-4 w-4 mr-2"})," Novo Cliente"]})]}),e.jsx(ke,{open:$,onOpenChange:t=>{t?z(!0):g()},children:e.jsxs(Ae,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Te,{children:e.jsxs(qe,{children:[i?"Editar":"Novo"," Cliente"]})}),e.jsxs("form",{onSubmit:t=>{t.preventDefault(),b.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(x,{children:"Código"}),e.jsx(C,{value:S,onChange:t=>_(t.target.value),placeholder:"Código do cliente"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(x,{children:"Nome"}),e.jsx(C,{value:m,onChange:t=>f(t.target.value),required:!0,placeholder:"Nome do cliente"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(x,{children:"CNPJ"}),e.jsx(C,{value:D,onChange:t=>E(t.target.value.replace(/\D/g,"").slice(0,14)),placeholder:"Somente números (14 dígitos)",inputMode:"numeric"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Usado para reconhecer XMLs de NF-e desse cliente no upload em lote."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(x,{children:"Logo do Cliente"}),e.jsxs("div",{className:"flex items-center gap-3",children:[Z&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Z,alt:"Logo",className:"h-16 w-16 object-contain rounded border"}),e.jsx("button",{type:"button",className:"absolute -top-1 -right-1 bg-destructive text-destructive-foreground rounded-full p-0.5",onClick:()=>{N(null),w(null),q(null)},children:e.jsx(me,{className:"h-3 w-3"})})]}),e.jsx("input",{ref:P,type:"file",accept:"image/*",className:"hidden",onChange:ge}),e.jsxs(u,{type:"button",variant:"outline",size:"sm",onClick:()=>{var t;return(t=P.current)==null?void 0:t.click()},children:[e.jsx(Fe,{className:"h-4 w-4 mr-1"})," ",Z?"Trocar":"Upload"]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(De,{id:"triangulacao_fiscal",checked:k,onCheckedChange:t=>A(t===!0)}),e.jsx(x,{htmlFor:"triangulacao_fiscal",children:"Triangulação Fiscal"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(x,{children:"Amostras de ração por produção"}
3),e.jsx(C,{type:"number",min:0,step:1,value:I,onChange:t=>T(Math.max(0,parseInt(t.target.value||"0",10)||0)),placeholder:"1"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Quantidade de etiquetas/amostras a coletar por produção. Use 0 para não coletar."})]}),i?e.jsx(Ke,{clienteId:i}):e.jsx("p",{className:"text-xs text-muted-foreground border rounded p-2 bg-muted/30",children:"Salve o cliente para cadastrar contatos e grupos do WhatsApp aqui."}),e.jsx(u,{type:"submit",className:"w-full",disabled:b.isPending,children:b.isPending?"Salvando...":"Salvar"})]})]})}),e.jsx("div",{className:"bg-card rounded-lg border",children:e.jsxs(le,{children:[e.jsxs(ce,{children:[e.jsxs(L,{className:"table-header",children:[e.jsx(r,{className:"w-16",children:"Logo"}),e.jsx(oe,{sortKey:"codigo",currentSort:V,onToggle:s,children:"Código"}),e.jsx(oe,{sortKey:"nome",currentSort:V,onToggle:s,children:"Nome"}),e.jsx(r,{className:"w-20 text-center",children:"Ativo"}),e.jsx(r,{className:"w-24",children:"Ações"})]}),e.jsxs(L,{children:[e.jsx(r,{}),e.jsx(r,{children:e.jsx(ae,{value:G.codigo||"",onChange:t=>J("codigo",t)})}),e.jsx(r,{children:e.jsx(ae,{value:G.nome||"",onChange:t=>J("nome",t)})}),e.jsx(r,{}),e.jsx(r,{})]})]}),e.jsx(de,{children:M?e.jsx(L,{children:e.jsx(c,{colSpan:5,className:"text-center text-muted-foreground",children:"Carregando..."})}):a.length===0?e.jsx(L,{children:e.jsx(c,{colSpan:5,className:"text-center text-muted-foreground",children:"Nenhum cliente encontrado"})}):a.map(t=>e.jsxs(L,{className:t.ativo===!1?"opacity-50":void 0,children:[e.jsx(c,{children:t.logo_url?e.jsx(Le,{src:t.logo_url,alt:"Logo",className:"h-8 w-8 object-contain rounded"}):e.jsx("div",{className:"h-8 w-8 bg-muted rounded flex items-center justify-center text-xs text-muted-foreground",children:"—"})}),e.jsx(c,{children:t.codigo}),e.jsx(c,{className:"font-medium",children:t.nome}),e.jsx(c,{className:"text-center",children:e.jsx(ee,{checked:t.ativo!==!1,onCheckedChange:n=>X.mutate({id:t.id,ativo:n})})}),e.jsx(c,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(u,{variant:"ghost",size:"icon",onClick:()=>je(t),children:e.jsx(he,{className:"h-4 w-4"})}),e.jsx(u,{variant:"ghost",size:"icon",onClick:()=>p.mutate(t.id),children:e.jsx(ue,{className:"h-4 w-4 text-destructive"})}),R&&e.jsx(Re,{tableName:"clientes",recordId:t.id})]})})]},t.id))})]})})]})}export{os 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.