1import{s as _,j as e,bF as U,bG as B,bH as F,bI as q,Z as C,B as E,ev as V,aA as G,c_ as D,d8 as K,ep as W,aQ as M,aR as Q,hq as Z,hr as H}from"./index-Ck3jlJIO.js";import{b as v}from"./charts-ytYDs0Yq.js";import{A as J}from"./AdminLayout-A-6FoqBw.js";import"./collapsible-B7wC1fNx.js";import"./categorias-de-parceiro-hIbo3PEn.js";const T=[{key:"auto_correction",label:"Auto-correção de cupons",emoji:"ðª",headerClass:"bg-purple-950/40 text-purple-300 border-purple-800/50",pillActiveClass:"bg-purple-600 text-white border-purple-500",pillInactiveClass:"bg-purple-950/40 text-purple-300 border-purple-800/50 hover:bg-purple-900/50"},{key:"availability",label:"Disponibilidade",emoji:"ð
",headerClass:"bg-amber-950/40 text-amber-300 border-amber-800/50",pillActiveClass:"bg-amber-600 text-white border-amber-500",pillInactiveClass:"bg-amber-950/40 text-amber-300 border-amber-800/50 hover:bg-amber-900/50"},{key:"agency_restriction",label:"Restrição por agência",emoji:"ð«",headerClass:"bg-pink-950/40 text-pink-300 border-pink-800/50",pillActiveClass:"bg-pink-600 text-white border-pink-500",pillInactiveClass:"bg-pink-950/40 text-pink-300 border-pink-800/50 hover:bg-pink-900/50"},{key:"invalid_coupon",label:"Cupom inválido / outros erros API",emoji:"â",headerClass:"bg-red-950/40 text-red-300 border-red-800/50",pillActiveClass:"bg-red-600 text-white border-red-500",pillInactiveClass:"bg-red-950/40 text-red-300 border-red-800/50 hover:bg-red-900/50"},{key:"input_validation",label:"Validação de entrada",emoji:"âï¸",headerClass:"bg-gray-800/60 text-gray-300 border-gray-700/50",pillActiveClass:"bg-gray-600 text-white border-gray-500",pillInactiveClass:"bg-gray-800/60 text-gray-300 border-gray-700/50 hover:bg-gray-700/60"},{key:"unexpected",label:"Erros inesperados",emoji:"ð¥",headerClass:"bg-red-950/60 text-red-200 border-red-700/60",pillActiveClass:"bg-red-800 text-white border-red-700",pillInactiveClass:"bg-red-950/60 text-red-200 border-red-700/60 hover:bg-red-900/60"}],k=[{key:"auto_correction",label:"Auto-correção de cupons",emoji:"ðª",headerClass:"bg-purple-950/40 text-purple-300 border-purple-800/50",pillActiveClass:"bg-purple-600 text-white border-purple-500",pillInactiveClass:"bg-purple-950/40 text-purple-300 border-purple-800/50 hover:bg-purple-900/50",categoryKeys:["auto_correction"]},{key:"invalid_coupon",label:"Cupom inválido",emoji:"â",headerClass:"bg-red-950/40 text-red-300 border-red-800/50",pillActiveClass:"bg-red-600 text-white border-red-500",pillInactiveClass:"bg-red-950/40 text-red-300 border-red-800/50 hover:bg-red-900/50",categoryKeys:["invalid_coupon"]},{key:"input_validation",label:"Validação de entrada",emoji:"âï¸",headerClass:"bg-gray-800/60 text-gray-300 border-gray-700/50",pillActiveClass:"bg-gray-600 text-white border-gray-500",pillInactiveClass:"bg-gray-800/60 text-gray-300 border-gray-700/50 hover:bg-gray-700/60",categoryKeys:["input_validation"]},{key:"errors_and_restrictions",label:"Erros & Restrições",emoji:"â ï¸",headerClass:"bg-amber-950/40 text-amber-300 border-amber-800/50",pillActiveClass:"bg-amber-600 text-white border-amber-500",pillInactiveClass:"bg-amber-950/40 text-amber-300 border-amber-800/50 hover:bg-amber-900/50",categoryKeys:["availability","agency_restriction","unexpected"]}];function Y(r){var a;const o=(r.message||"").toLowerCase(),n=String(((a=r.payload)==null?void 0:a.apiError)??"").toLowerCase();return o.includes("auto-corrected")||o.includes("fuzzy")||o.includes("no fuzzy candidate")?"auto_correction":o.includes("agency restriction")?"agency_restriction":o.includes("validation failed")?/disponibilidade|indispon|não dispon|nao dispon/.test(n)?"availability":"invalid_coupon":o.startsWith("validation:")||o.includes("region config")||o.includes("resolve local paths")||o.includes("no valid items")?"input_validation":o.includes("unexpected error")?"unexpected":"invalid_coupon"}async function A(r){var m;const o=new Set;for(const i of r){const d=(m=i.payload)==null?void 0:m.product_names;if(d)for(const p of d)p.includes("/")&&o.add(p);if(i.payload&&!d){const p=i.payload.products;if(p)for(const l of p)l.path&&o.add(l.path)}}if(o.size===0)return r;const n=Array.from(o),a={},{data:f}=await _.from("product_travel3_config").select("travel3_product_path, product_id").in("travel3_product_path",n);if(f&&f.length>0){const i=[...new Set(f.map(l=>l.product_id))],{data:d}=await _.from("products").select("id, name").in("id",i),p=Object.fromEntries((d||[]).map(l
1=>[l.id,l.name]));for(const l of f)p[l.product_id]&&(a[l.travel3_product_path]=p[l.product_id])}const g=n.filter(i=>!a[i]);if(g.length>0){const i=s=>s.startsWith("products/combos/")?s.replace("products/combos/","productCombos/"):s.startsWith("combos/")?s.replace("combos/","productCombos/"):s,d={},p=[];for(const s of g){const t=i(s);d[t]=s,p.push(t),p.includes(s)||p.push(s)}const{data:l}=await _.from("travel3_products_cache").select("product_path, product_name").in("product_path",p);if(l)for(const s of l){const t=d[s.product_path]||s.product_path;a[t]||(a[t]=s.product_name),d[s.product_path]&&!a[d[s.product_path]]&&(a[d[s.product_path]]=s.product_name)}}const x=n.filter(i=>!a[i]);if(x.length>0){const i=s=>{const t=[s],u=s.match(/(\d+)$/);if(!u)return t;const c=u[1];return t.push(`products/${c}`,`combos/${c}`,`productCombos/${c}`,`products/combos/${c}`),[...new Set(t)]},d=[],p={};for(const s of x)for(const t of i(s))d.push(t),p[t]=s;const{data:l}=await _.from("order_items").select("travel3_product_path, product_id").in("travel3_product_path",d).limit(50);if(l&&l.length>0){const s=[...new Set(l.map(u=>u.product_id))],{data:t}=await _.from("products").select("id, name").in("id",s);if(t){const u=Object.fromEntries(t.map(c=>[c.id,c.name]));for(const c of l){const b=p[c.travel3_product_path];b&&!a[b]&&u[c.product_id]&&(a[b]=u[c.product_id])}}}}return r.map(i=>{var p;const d=(p=i.payload)==null?void 0:p.product_names;if(d&&d.some(l=>l.includes("/"))){const l=d.map(s=>a[s]||s);return{...i,payload:{...i.payload,product_names:l}}}if(i.payload&&!d){const l=i.payload.products;if(l){const s=l.map(t=>t.path?a[t.path]||t.path:null).filter(Boolean);if(s.length>0)return{...i,payload:{...i.payload,product_names:s}}}}return i})}const S=[{id:"travel3-create-block",label:"travel3-create-block",functionName:"travel3-create-block"},{id:"travel3-validate-coupon",label:"travel3-validate-coupon",functionName:"travel3-validate-coupon"},{id:"travel3-webhook",label:"travel3-webhook",functionName:"travel3-webhook"},{id:"travel3-send-access-list",label:"travel3-send-access-list",functionName:"travel3-send-access-list"},{id:"getAccessList",label:"getAccessList",functionName:"travel3-send-access-list",messagePrefix:"getAccessList"},{id:"discord-daily-sales-report",label:"discord-daily-sales-report",functionName:"discord-daily-sales-report"}],X=new Set(["travel3-create-block"]),ee=new Set(["travel3-validate-coupon"]),te=r=>{switch(r){case"error":return"text-red-400";case"warn":return"text-yellow-400";case"info":return"text-blue-400";default:return"text-gray-400"}},R=({log:r})=>{var n;const o=((n=r.payload)==null?void 0:n.product_names)||[];return e.jsxs("div",{className:"p-3 hover:bg-gray-900/50",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-gray-500 shrink-0 w-[140px]",children:new Date(r.created_at).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}),e.jsx("span",{className:`uppercase font-bold shrink-0 w-[50px] ${te(r.level)}`,children:r.level}),e.jsx("span",{className:"text-gray-200",children:r.message})]}),o.length>0&&e.jsx("div",{className:"mt-1.5 ml-[193px] flex flex-wrap gap-1.5",children:o.map((a,f)=>{const g=a.includes("/");return e.jsx(D,{variant:"secondary",className:g?"bg-gray-800/60 text-gray-500 border-gray-700/50 text-[11px] font-mono":"bg-blue-900/40 text-blue-300 border-blue-700/50 text-[11px]",children:a},f)})}),r.payload&&e.jsx("pre",{className:"mt-2 ml-[193px] text-gray-400 whitespace-pre-wrap break-all",children:JSON.stringify(r.payload,null,2)})]})},P=({loading:r,onRefresh:o,onClear:n,realtimeConnected:a,errorsOnly:f,count:g,lastUpdated:x})=>e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(E,{variant:"outline",size:"sm",onClick:o,disabled:r,children:[e.jsx(V,{className:`w-4 h-4 mr-2 ${r?"animate-spin":""}`}),"Atualizar"]}),e.jsxs(E,{variant:"outline",size:"sm",onClick:n,className:"text-destructive",children:[e.jsx(G,{className:"w-4 h-4 mr-2"}),"Limpar"]}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-auto flex items-center gap-2",children:[f&&e.jsxs(e.Fragment,{children:[e.jsx(D,{variant:"destructive",className:"text-[10px] uppercase",children:"Exibindo apenas erros"}),e.jsx("span",{className:"text-muted-foreground",children:"â¢"})]}),a?e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(K,{className:"w-3.5 h-3.5"})," Ao vivo"]}):e.jsxs("span",{className:"flex items-center gap-1 text-yellow-500",children:[e.jsx(W,{className:"w-3.5 h-3.5"})," Polling 10s"]}),e.jsx("span",{className:"text-muted-foreground",children:"â¢"}),g," log(s)",x&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"â¢"}),"Atualizado ",x.toLocaleTimeString("pt-BR")]})]})]});function $(r,o){const{functionName:n,messagePrefix:a}=r,[f,g]=v.useState([]),[x,m]=v.useState(!0),[i,d]=v.useState(null),[p,l]=v.useState(!1),s=v.useRef([]),t=v.useCallback(async()=>{m(!0);let c=_.from("edge_function_logs").select("*").eq("function_name",n);a&&(c=c.like("message",`${a}%`)),o&&(c=c.eq("level","error"));const{data:b,error:y}=await c.order("created_at",{ascending:!1}).limit(100);if(y)C({title:"Erro ao carregar logs",description:y.message,variant:"destructive"}),g([]),s.current=[];else{const h=await A(b||[]);g(h),s.current=h}m(!1),d(new Date)},[n,a,o]);return v.useEffect(()=>{t();const c=`edge-logs:${r.id}`,b=_.channel(c).on("postgres_changes",{event:"INSERT",schema:"public",table:"edge_function_logs",filter:`function_name=eq.${n}`},async h=>{const j=h.new;if(a&&!String(j.message||"").startsWith(a)||o&&j.level!=="error"||s.current.some(L=>L.id===j.id))return;const N=(await A([j]))[0];g(L=>{const I=[N,...L.filter(O=>O.id!==N.id)].slice(0,100);return s.current=I,I}),d(new Date)}).subscribe(h=>
1{l(h==="SUBSCRIBED")}),y=setInterval(async()=>{let h=_.from("edge_function_logs").select("*").eq("function_name",n);a&&(h=h.like("message",`${a}%`)),o&&(h=h.eq("level","error"));const{data:j}=await h.order("created_at",{ascending:!1}).limit(100);if(j){const N=await A(j||[]);g(N),s.current=N,d(new Date)}},1e4),w=()=>{document.visibilityState==="visible"&&t()};return document.addEventListener("visibilitychange",w),()=>{_.removeChannel(b),clearInterval(y),document.removeEventListener("visibilitychange",w)}},[t,n,a,r.id,o]),{logs:f,loading:x,lastUpdated:i,realtimeConnected:p,fetchLogs:t,clearLogs:async()=>{let c=_.from("edge_function_logs").delete().eq("function_name",n);a&&(c=c.like("message",`${a}%`));const{error:b}=await c;b?C({title:"Erro ao limpar logs",description:b.message,variant:"destructive"}):(g([]),s.current=[],C({title:"Logs limpos"}))}}}const re=()=>{const{year:r,month:o,day:n}=H(),a=new Date(Date.UTC(r,o-1,n));return a.setUTCDate(a.getUTCDate()-1),a.toISOString().slice(0,10)},ae=({onEnviado:r})=>{const o=re(),[n,a]=v.useState(o),[f,g]=v.useState(!1),x=async()=>{g(!0);try{const{data:m,error:i}=await _.functions.invoke("discord-daily-sales-report",{body:{date:n}});if(i)throw i;if(m&&m.ok===!1)throw new Error(m.error||"falha no envio");C({title:"Relatório enviado",description:`Fechamento de ${n} publicado no Discord.`}),r()}catch(m){C({title:"Não enviou",description:m instanceof Error?m.message:String(m),variant:"destructive"})}finally{g(!1)}};return e.jsxs("div",{className:"flex flex-wrap items-end gap-3 rounded-lg border border-border bg-muted/30 p-3",children:[e.jsxs("div",{children:[e.jsx(M,{htmlFor:"reenvio-data",className:"text-xs",children:"Reenviar fechamento de"}),e.jsx(Q,{id:"reenvio-data",type:"date",className:"mt-1.5 w-44",value:n,max:o,onChange:m=>a(m.target.value)})]}),e.jsxs(E,{size:"sm",onClick:x,disabled:f||!n,children:[e.jsx(Z,{className:`w-4 h-4 mr-2 ${f?"animate-pulse":""}`}),f?"Enviando...":"Enviar ao Discord"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Só dia já encerrado em BRT â a função recusa dia em andamento, que sairia como fechamento parcial."})]})},se=({scope:r})=>{const o=!r.messagePrefix&&X.has(r.functionName),{logs:n,loading:a,lastUpdated:f,realtimeConnected:g,fetchLogs:x,clearLogs:m}=$(r,o);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(P,{loading:a,onRefresh:x,onClear:m,realtimeConnected:g,errorsOnly:o,count:n.length,lastUpdated:f}),r.functionName==="discord-daily-sales-report"&&!r.messagePrefix&&e.jsx(ae,{onEnviado:x}),e.jsx("div",{className:"bg-gray-950 rounded-lg border border-border overflow-auto max-h-[70vh] font-mono text-xs",children:n.length===0?e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:a?"Carregando...":"Nenhum log encontrado."}):e.jsx("div",{className:"divide-y divide-gray-800",children:n.map(i=>e.jsx(R,{log:i},i.id))})})]})},oe=({scope:r})=>{const{logs:o,loading:n,lastUpdated:a,realtimeConnected:f,fetchLogs:g,clearLogs:x}=$(r,!1),[m,i]=v.useState(null),d=v.useMemo(()=>{const t=new Map;for(const u of T)t.set(u.key,[]);for(const u of o){const c=Y(u);t.get(c).push(u)}return t},[o]),p=v.useMemo(()=>{const t={};for(const u of T)t[u.key]=u;return t},[]),l=v.useMemo(()=>{const t={};for(const u of k)t[u.key]=u.categoryKeys.reduce((c,b)=>{var y;return c+(((y=d.get(b))==null?void 0:y.length)||0)},0);return t},[d]),s=m?k.filter(t=>t.key===m):k;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(P,{loading:n,onRefresh:g,onClear:x,realtimeConnected:f,errorsOnly:!1,count:o.length,lastUpdated:a}),e.jsxs("div",{className:"flex flex-wrap gap-2 p-3 rounded-lg border border-border bg-black",children:[e.jsxs("button",{type:"button",onClick:()=>i(null),className:`text-xs px-3 py-1.5 rounded-full border transition-colors font-medium ${m===null?"bg-primary text-primary-foreground border-primary":"bg-gray-800/60 text-gray-300 border-gray-700/50 hover:bg-gray-700/60"}`,children:["Todos ",o.length]}),k.map(t=>{const u=m===t.key;return e.jsxs("button",{type:"button",onClick:()=>i(u?null:t.key),className:`text-xs px-3 py-1.5 rounded-full border transition-colors font-medium ${u?t.pillActiveClass:t.pillInactiveClass}`,children:[t.emoji," ",t.label," ",l[t.key]]},t.key)})]}),e.jsx("div",{className:"bg-gray-950 rounded-lg border border-border overflow-auto max-h-[70vh] font-mono text-xs",children:o.length===0?e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:n?"Carregando...":"Nenhum log encontrado."}):e.jsx("div",{children:s.map(t=>{const u=l[t.key];if(u===0)return null;const c=t.categoryKeys.length>1;return e.jsxs("div",{children:[e.jsxs("div",{className:`sticky top-0 z-10 px-3 py-2 border-b border-t font-semibold text-[11px] uppercase tracking-wide ${t.headerClass}`,children:[t.emoji," ",t.label," (",u,")"]}),c?t.categoryKeys.map(b=>{const y=d.get(b)||[];if(y.length===0)return null;const w=p[b];return e.jsxs("div",{children:[e.jsxs("div",{className:"px-3 py-1.5 border-b border-gray-800 bg-gray-900/60 text-[10px] uppercase tracking-wide text-gray-400 font-medium",children:[w.emoji," ",w.label," (",y.length,")"]}),e.jsx("div",{className:"divide-y divide-gray-800",children:y.map(h=>e.jsx(R,{log:h}
1,h.id))})]},b)}):e.jsx("div",{className:"divide-y divide-gray-800",children:(d.get(t.categoryKeys[0])||[]).map(b=>e.jsx(R,{log:b},b.id))})]},t.key)})})})]})},ue=()=>e.jsx(J,{title:"Edge Function Logs",subtitle:"travel3-create-block: somente erros ⢠travel3-validate-coupon: todos os nÃveis, agrupados por categoria",children:e.jsxs(U,{defaultValue:S[0].id,className:"w-full",children:[e.jsx(B,{children:S.map(r=>e.jsx(F,{value:r.id,className:"font-mono text-xs",children:r.label},r.id))}),S.map(r=>e.jsx(q,{value:r.id,children:!r.messagePrefix&&ee.has(r.functionName)?e.jsx(oe,{scope:r}):e.jsx(se,{scope:r})},r.id))]})});export{ue 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.