PageSourceSearch

https://epicos.ai/assets/index-DQd7c3ah.js

js epicos.ai collected 2026-10-05 13:30:42 UTC 62,738 bytes, 1 lines download raw bytes

1import{j as e,a8 as U,bt as z,c as S,B as Cs,H as ks,I as Ss,J as $s,ak as Ds,aj as Ms,t as B,n as me,b0 as xe,ae as We,at as Je,f3 as Ze,u as As,P as Fs,X as Es,R as Ts,S as Os,U as Ps,V as Is,W as Ls,bN as qs,bO as Bs,bP as ie,bQ as ee}from"./index-DdokvTmJ.js";import{T as Rs,r as d,ag as ke,aw as Us,C as es,L as ue,bT as ss,d as zs,X as ms,bp as Hs,g as Vs,bD as Gs,bU as Xs}from"./lucide-icons-DcjOfOJe.js";import{u as g,b as X,n as xs,i as M,t as ae,a as us,s as Ys,c as he,l as ts,d as Qs,e as Ks,r as Ws,p as Js,f as as,g as je,R as rs,h as Zs,j as et}from"./RastreioAgentes-shiSw7Wd.js";import{R as st,v as tt,X as at,Y as rt,T as ot,B as nt}from"./generateCategoricalChart-CbeY6FJ0.js";import{B as it}from"./BarChart-2aqBF0aD.js";import"./path-CXeFd1JH.js";import"./string-C73urjQZ.js";import"./band-CquvqAHh.js";import"./init-Dmth1JHB.js";import"./ordinal-DILIJJjt.js";import"./linear-0NWxi4eL.js";import"./time-D6btX2Yz.js";import"./array-BKyUJesY.js";import"./line-L_YPMc3M.js";const lt="Outros usos do ambiente",hs=new Set(["Instagram"]);function ct(s,r){return r===1?s:s==="conversa"?"conversas":"gerações"}function dt({linha:s}){const r=s.custo_min_unidade,o=s.custo_max_unidade,n=s.custo_medio_unidade;if(n==null||r==null||o==null)return e.jsx("span",{className:"text-[var(--text-3)]",children:"—"});const u=n>0&&o/n>=5;return e.jsxs("div",{className:"min-w-[170px]",children:[e.jsxs("div",{className:"tabular-nums text-[var(--text-1)]",children:[e.jsx("span",{className:"font-medium",children:g(n)})," ",e.jsx("span",{className:"text-[11px] font-normal text-[var(--text-3)]",children:"em média"})]}),o>r&&e.jsxs("div",{className:"mt-0.5 text-[11px] tabular-nums text-[var(--text-3)]",children:["varia de ",g(r)," a ",g(o)]}),u&&e.jsxs("div",{className:"mt-0.5 text-[11px] text-[var(--warning)]",children:["a mais cara custou ",Math.round(o/n),"× a média"]})]})}function os({linha:s}){return s.sem_consumo?e.jsx("span",{className:"text-[11px] text-[var(--text-3)]",children:hs.has(s.origem)?"não conectado":"sem uso no período"}):s.unidades>0?e.jsxs("span",{className:"tabular-nums",children:[M(s.unidades)," ",e.jsx("span",{className:"text-[11px] text-[var(--text-3)]",children:ct(s.unidade,s.unidades)})]}):e.jsx("span",{className:"text-[11px] text-[var(--text-3)]",children:"unidade não registrada"})}function mt({origens:s,cambio:r,selecionada:o,onSelecionar:n}){const[u,m]=d.useState(null);d.useEffect(()=>{o&&m(o)},[o]);const c=s.filter(l=>!l.pai),p=l=>s.filter(b=>b.pai===l);if(s.length===0)return e.jsx(U,{children:e.jsx(z,{className:"p-6 text-sm text-[var(--text-2)]",children:"Nenhum consumo registrado neste período."})});const a=c.filter(l=>l.origem!==lt||!l.sem_consumo).filter(l=>!o||l.origem===o),w=a.reduce((l,b)=>l+(Number(b.custo_usd)||0),0),I=a.filter(l=>!l.sem_consumo),D=o?null:I[0],N=D&&w>0?Number(D.custo_usd)/w*100:0;return e.jsx(U,{children:e.jsxs(z,{className:"p-4 md:p-5",children:[o&&e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsx("button",{onClick:()=>n(null),className:"text-[11px] text-[var(--text-2)] underline hover:text-[var(--text-1)]",children:"ver todas as origens"})}),D&&e.jsxs("p",{className:"mb-3 text-sm text-[var(--text-2)]",children:[e.jsx("strong",{className:"font-semibold text-[var(--text-1)]",children:D.origem})," responde por ",N.toFixed(N>=10?0:1),"% do custo do período"," ","(",g(D.custo_usd)," de ",g(w),")."]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-[var(--n200)] text-[11px] uppercase tracking-wider text-[var(--text-3)]",children:[e.jsx("th",{className:"py-2 pr-4 text-left font-medium",children:"origem"}),e.jsx("th",{className:"py-2 pr-4 text-left font-medium",children:"usos"}),e.jsx("th",{className:"py-2 pr-4 text-right font-medium",children:"tokens"}),e.jsxs("th",{className:"py-2 pr-4 text-left font-medium",children:["por ",a.some(l=>l.unidade==="conversa")?"conversa":"geração"]}),e.jsx("th",{className:"py-2 text-right font-medium",children:"total"})]})}),e.jsxs("tbody",{children:[a.map(l=>{const b=p(l.origem),y=u===l.origem&&b.length>0,C=X(l.custo_usd,r),_=b.reduce(($,Q)=>$+(Number(Q.custo_usd)||0),0),f=(Number(l.custo_usd)||0)-_,L=l.origem==="Chat Institucional"?"canais":"aplicações",E='relative before:absolute before:left-[9px] before:top-0 before:bottom-0 before:w-0.5 before:bg-[var(--brand-20)] before:content-[""]';return[e.jsxs("tr",{className:S("border-b border-[var(--n200)] transition-colors",l.sem_consumo&&"text-[var(--text-3)]",y?"bg-[var(--bg-2)]":"hover:bg-[var(--surface-hover)]",o===l.origem&&"bg-[var(--brand-10)]"),children:[e.jsxs("td",{className:"py-3 pr-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[b.length>0?e.jsx("button",{onClick:()=>m(y?null:l.origem),"aria-expanded":y,"aria-label":`Detalhar ${l.origem}`,className:"flex h-[18px] w-[18px] shrink-0 items-center justify-center rounded-[var(--radius-sm)] text-[var(--text-3)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-1)]",children:e.jsx(ke,{className:S("h-3.5 w-3.5 transition-transform duration-150",y?"rotate-0":"-rotate-90")})}
1):e.jsx("span",{"aria-hidden":!0,className:"flex h-[18px] w-[18px] shrink-0 items-center justify-center",children:e.jsx("span",{className:S("h-1.5 w-1.5 rounded-full",l.sem_consumo?"bg-[var(--n200)]":"bg-[var(--n300)]")})}),e.jsx("button",{onClick:()=>n(o===l.origem?null:l.origem),className:S("text-left font-medium hover:underline",l.sem_consumo?"text-[var(--text-2)]":"text-[var(--text-1)]"),children:l.origem})]}),e.jsxs("div",{className:"ml-[26px] mt-0.5 text-[11px] leading-tight text-[var(--text-3)]",children:[l.sem_consumo?l.aplicacoes_cadastradas?`${M(l.aplicacoes_cadastradas)} cadastrado(s), nenhum uso no período`:"nenhum uso no período":`${M(l.chamadas)} chamadas ao modelo`,b.length>0&&` · ${b.length} ${L}`,l.chamadas_sem_custo>0&&e.jsxs(Cs,{variant:"secondary",className:"ml-2 px-1.5 py-0 text-[10px] font-normal",children:[M(l.chamadas_sem_custo)," sem custo apurado"]})]})]}),e.jsx("td",{className:"py-3 pr-4",children:e.jsx(os,{linha:l})}),e.jsx("td",{className:"py-3 pr-4 text-right tabular-nums text-[var(--text-2)]",children:ae(Number(l.tokens))}),e.jsx("td",{className:"py-3 pr-4",children:e.jsx(dt,{linha:l})}),e.jsxs("td",{className:"relative py-3 text-right",children:[!l.sem_consumo&&w>0&&e.jsx("span",{"aria-hidden":!0,className:"absolute inset-y-1.5 right-0 rounded-[var(--radius-sm)] bg-[var(--brand)]/10",style:{width:`${Number(l.custo_usd)/w*100}%`}}),e.jsx("div",{className:S("relative tabular-nums font-semibold",l.sem_consumo?"text-[var(--text-3)]":"text-[var(--text-1)]"),children:g(l.custo_usd)}),C&&e.jsx("div",{className:"relative text-[11px] tabular-nums text-[var(--text-3)]",children:C})]})]},l.origem),...y?[e.jsx("tr",{className:"bg-[var(--bg-2)]",children:e.jsx("td",{colSpan:5,className:S("pb-1.5 pl-8 pr-4 pt-1 text-[11px] font-medium uppercase tracking-wider text-[var(--text-3)]",E),children:l.origem==="Chat Institucional"?"Canais de entrada":"Aplicações que geraram"})},`${l.origem}-titulo`),...b.map($=>e.jsxs("tr",{className:S("bg-[var(--bg-2)] text-[13px]",$.sem_consumo&&"opacity-70"),children:[e.jsx("td",{className:S("py-2 pl-8 pr-4 text-[var(--text-2)]",E),children:$.origem}),e.jsx("td",{className:"py-2 pr-4",children:e.jsx(os,{linha:$})}),e.jsx("td",{className:"py-2 pr-4 text-right tabular-nums text-[var(--text-3)]",children:$.sem_consumo?"—":ae(Number($.tokens))}),e.jsx("td",{className:"py-2 pr-4 tabular-nums text-[var(--text-3)]",children:$.custo_medio_unidade!=null?g($.custo_medio_unidade):"—"}),e.jsx("td",{className:"py-2 text-right tabular-nums font-normal text-[var(--text-2)]",children:hs.has($.origem)?"—":g($.custo_usd)})]},$.origem)),e.jsxs("tr",{className:"border-b-2 border-[var(--n300)] bg-[var(--bg-2)]",children:[e.jsxs("td",{colSpan:4,className:"relative py-2 pl-8 pr-4 text-[11px] text-[var(--text-3)] before:absolute before:left-[9px] before:top-0 before:h-[17px] before:w-0.5 before:bg-[var(--brand-20)] before:content-[''] after:absolute after:left-[9px] after:top-[15px] after:h-0.5 after:w-3 after:bg-[var(--brand-20)] after:content-['']",children:["Soma d",b.length===1?"o":"os"," ",b.length," ",L," — já contabilizada na linha ",l.origem," acima",f>5e-5&&e.jsxs("span",{className:"ml-1",children:["· ",e.jsx("strong",{className:"font-medium",children:g(f)})," sem"," ",l.origem==="Chat Institucional"?"canal":"aplicação"," identificad",l.origem==="Chat Institucional"?"o":"a"]})]}),e.jsx("td",{className:"py-2 text-right text-[11px] tabular-nums text-[var(--text-3)]",children:g(_)})]},`${l.origem}-soma`)]:[]]}),!o&&e.jsxs("tr",{className:"border-t-2 border-[var(--n300)]",children:[e.jsxs("td",{className:"py-3 pl-[26px] pr-4 text-[var(--text-2)]",children:["Total das origens"," ",e.jsx("span",{className:"text-[11px] text-[var(--text-3)]",children:"(custo apurado)"})]}),e.jsx("td",{colSpan:3}),e.jsxs("td",{className:"py-3 text-right",children:[e.jsx("div",{className:"tabular-nums text-[15px] font-semibold text-[var(--text-1)]",children:g(w)}),X(w,r)&&e.jsx("div",{className:"text-[11px] tabular-nums text-[var(--text-3)]",children:X(w,r)})]})]})]})]})})]})})}function xt({cobertura:s,atribuicao:r,cambio:o}){var D;const n=Number(s==null?void 0:s.chamadas)||0,u=Number(s==null?void 0:s.chamadas_com_custo)||0,m=(D=s==null?void 0:s.modelos_sem_preco)!=null?D:[],c=n>0?u/n*100:100,p=Number(r==null?void 0:r.custo_aluno)||0,a=Number(r==null?void 0:r.custo_anonimo)||0,w=p+a,I=w>0?p/w*100:0;return n===0||m.length===0?e.jsx(U,{children:e.jsxs(z,{className:"flex flex-wrap items-center justify-between gap-x-6 gap-y-2 p-4 text-xs",children:[e.jsx("span",{className:"font-medium uppercase tracking-wider text-[var(--text-3)]",children:"Confiança do dado"}),e.jsxs("span",{className:"text-[var(--text-2)]",children:[e.jsxs("strong",{className:"tabular-nums text-[var(--text-1)]",children:[c.toFixed(0),"%"]})," das chamadas com custo apurado",w>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("strong",{className:"tabular-nums text-[var(--text-1)]",children:[I.toFixed(0),"%"]}
1)," ","do custo ligado a aluno identificado (",g(p),o&&X(p,o)?`, ${X(p,o)}`:"","), o resto anônimo antes da identificação"]})]})]})}):e.jsx(U,{className:"border-[var(--warning)]/40 bg-[var(--warning-bg)]",children:e.jsx(z,{className:"p-4 md:p-5",children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx(Rs,{className:"mt-0.5 h-4 w-4 shrink-0 text-[var(--warning)]"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-sm font-medium text-[var(--text-1)]",children:[c.toFixed(0),"% das chamadas têm custo apurado"]}),e.jsx("p",{className:"mt-0.5 text-xs text-[var(--text-2)]",children:"O restante roda em modelo sem preço cadastrado: o consumo aconteceu, mas não entra em nenhum total desta tela. Cadastre o preço na tela de modelos para o número fechar."}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-[var(--n200)] text-[11px] uppercase tracking-wider text-[var(--text-3)]",children:[e.jsx("th",{className:"py-1.5 pr-4 text-left font-medium",children:"modelo sem preço"}),e.jsx("th",{className:"py-1.5 pr-4 text-right font-medium",children:"chamadas"}),e.jsx("th",{className:"py-1.5 text-right font-medium",children:"tokens"})]})}),e.jsx("tbody",{children:m.map(N=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"max-w-[320px] truncate py-1.5 pr-4",children:xs(N.modelo)}),e.jsx("td",{className:"py-1.5 pr-4 text-right tabular-nums text-[var(--text-2)]",children:M(N.chamadas)}),e.jsx("td",{className:"py-1.5 text-right tabular-nums",children:ae(Number(N.tokens))})]},N.modelo))})]})})]})]})})})}function ps({aria:s,opcoes:r,valor:o,onChange:n,compacto:u=!1}){return e.jsx("div",{role:"group","aria-label":s,className:S("flex flex-wrap items-center gap-1 rounded-[var(--radius-md)] border border-[var(--n200)]",u?"bg-[var(--bg-2)] p-0.5":"bg-[var(--bg-3)] p-1"),children:r.map(m=>{const c=o===m.valor;return e.jsx("button",{onClick:()=>n(m.valor),"aria-pressed":c,title:m.titulo,className:S("rounded-[var(--radius-sm)] font-medium transition-colors",u?"px-2 py-1 text-[11px]":"px-3 py-1.5 text-xs",c?"bg-[var(--brand)] text-white":"text-[var(--text-2)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-1)]"),children:m.rotulo},String(m.valor))})})}const ut=s=>{const r=String(s.getMonth()+1).padStart(2,"0"),o=String(s.getDate()).padStart(2,"0");return`${s.getFullYear()}-${r}-${o}`},ns=s=>{const[r,o,n]=s.slice(0,10).split("-");return`${n}/${o}`},ht=s=>{const[r,o,n]=s.slice(0,10).split("-");return`${n}/${o}/${r}`},pt=s=>`US$ ${s.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})}`;function vt({serie:s,dias:r,periodo:o,origem:n,opcoesOrigem:u}){const[m,c]=d.useState(null),[p,a]=d.useState(null),[w,I]=d.useState(!1);d.useEffect(()=>{n&&c(null)},[n]),d.useEffect(()=>{if(!m){a(null);return}let y=!0;return I(!0),us(r,1,"todos",m,o!=null?o:null).then(C=>{var _;return y&&a((_=C.serie)!=null?_:[])}).catch(()=>y&&a([])).finally(()=>y&&I(!1)),()=>{y=!1}},[m,r,o==null?void 0:o.inicio,o==null?void 0:o.fim]);const D=p!=null?p:s,N=d.useMemo(()=>s.reduce((y,C)=>y+(Number(C.custo_usd)||0),0),[s]),l=d.useMemo(()=>{const y=new Map(D.map(_=>[_.dia.slice(0,10),_])),C=o?new Date(o.inicio+"T12:00:00"):(()=>{const _=new Date;return _.setHours(12,0,0,0),_.setDate(_.getDate()-(r-1)),_})();return Array.from({length:Math.max(1,r)},(_,f)=>{var $;const L=new Date(C);L.setDate(C.getDate()+f);const E=ut(L);return($=y.get(E))!=null?$:{dia:E,custo_usd:0,chamadas:0}})},[D,r,o]),b=d.useMemo(()=>{if(l.length===0)return{media:0,total:0,pico:null};const y=l.reduce((_,f)=>Number(f.custo_usd)>Number(_.custo_usd)?f:_),C=l.reduce((_,f)=>_+Number(f.custo_usd||0),0);return{media:C/l.length,total:C,pico:y}},[l]);return s.length===0?e.jsx("p",{className:"py-10 text-center text-sm text-[var(--text-3)]",children:"Nenhum custo registrado neste período."}):e.jsxs("div",{children:[!n&&u&&u.length>2&&e.jsx("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:e.jsx(ps,{aria:"Origem do consumo neste gráfico",compacto:!0,valor:m,onChange:y=>c(y),opcoes:u})}),e.jsxs("div",{className:"mb-3 flex flex-wrap items-baseline justify-between gap-x-6 gap-y-1",children:[e.jsxs("p",{className:"text-sm text-[var(--text-2)]",children:["As barras somam"," ",e.jsx("strong",{className:"tabular-nums font-semibold text-[var(--text-1)]",children:g(b.total)}),m?e.jsxs(e.Fragment,{children:[" ","de ",e.jsx("strong",{className:"font-semibold text-[var(--text-1)]",children:m})," — recorte só deste gráfico. O total da página segue em"," ",e.jsx("span",{className:"tabular-nums",children:g(N)}),"."]}):n?e.jsxs(e.Fragment,{children:[" ","de ",e.jsx("strong",{className:"font-semibold text-[var(--text-1)]",children:n})," — o mesmo custo do topo, dia a dia."]}):e.jsx(e.Fragment,{children:" — o custo de todas as origens somadas, dia a dia. É o mesmo total do topo."})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-5 text-[11px] text-[var(--text-3)]",children:[e.jsxs("span",{children:["média por dia"," ",e.jsx("strong",{className:"tabular-nums text-[var(--text-1)]",children:g(b.media)})]}),b.pico&&Number(b.pico.custo_usd)>0&&e.jsxs("span",{children:["pico ",e.jsx("strong",{className:"tabular-nums text-[var(--text-1)]",children:g(b.pico.custo_usd)})," ","em ",ns(b.pico.dia)]})]})]}),e.jsx("div",{className:S("h-[220px] w-full transition-opacity",w&&"opacity-40"),role:"img","aria-label":`Custo diário dos últimos ${r} dias`,children:e.jsx(st,{width:"100%",height:"100%",children:e.jsxs(it,{data:l,margin:{top:8,right:8,bottom:4,left:0},children:[e.jsx(tt,{vertical:!1,stroke:"var(--n200)",strokeDasharray:"3 3"}
1),e.jsx(at,{dataKey:"dia",axisLine:{stroke:"var(--n200)"},tickLine:!1,tick:{fontSize:11,fill:"var(--text-3)"},tickFormatter:ns,minTickGap:28,interval:"preserveStartEnd",dy:8}),e.jsx(rt,{axisLine:!1,tickLine:!1,tick:{fontSize:11,fill:"var(--text-3)"},tickFormatter:y=>pt(Number(y)),width:70}),e.jsx(ot,{cursor:{fill:"var(--bg-2)"},content:({active:y,payload:C})=>{if(!y||!(C!=null&&C.length))return null;const _=C[0].payload;return e.jsxs("div",{className:"min-w-44 rounded-[var(--radius-md)] border border-[var(--n200)] bg-[var(--bg-3)] p-3 shadow-sm",children:[e.jsx("p",{className:"text-xs font-medium text-[var(--text-1)]",children:ht(_.dia)}),e.jsxs("div",{className:"mt-2 space-y-1.5 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between gap-5",children:[e.jsx("span",{className:"text-[var(--text-2)]",children:"Custo"}),e.jsx("strong",{className:"tabular-nums text-[var(--text-1)]",children:g(_.custo_usd)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-5",children:[e.jsx("span",{className:"text-[var(--text-2)]",children:"Chamadas"}),e.jsx("strong",{className:"tabular-nums text-[var(--text-1)]",children:M(_.chamadas)})]})]})]})}}),e.jsx(nt,{dataKey:"custo_usd",fill:"var(--brand)",fillOpacity:.72,maxBarSize:30,radius:[4,4,0,0],activeBar:{fill:"var(--brand)",fillOpacity:1}})]})})})]})}const te=s=>`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")}`,is=s=>{const[r,o,n]=s.split("-");return`${n}/${o}/${r}`},Ne=(s,r)=>{const[o,n,u]=s.split("-"),[m,c,p]=r.split("-");return s===r?`${u}/${n}/${o}`:o===m?`${u}/${n} – ${p}/${c}/${m}`:`${is(s)} – ${is(r)}`},Y=()=>{const s=new Date;return s.setHours(12,0,0,0),s},ye=s=>{const r=Y();return r.setDate(r.getDate()-s),r},ve=[{chave:"7d",rotulo:"Últimos 7 dias",calcular:()=>({inicio:ye(6),fim:Y()})},{chave:"30d",rotulo:"Últimos 30 dias",calcular:()=>({inicio:ye(29),fim:Y()})},{chave:"90d",rotulo:"Últimos 90 dias",calcular:()=>({inicio:ye(89),fim:Y()})},{chave:"mes",rotulo:"Este mês",calcular:()=>{const s=Y();return{inicio:new Date(s.getFullYear(),s.getMonth(),1,12),fim:s}}},{chave:"mes_passado",rotulo:"Mês passado",calcular:()=>{const s=Y();return{inicio:new Date(s.getFullYear(),s.getMonth()-1,1,12),fim:new Date(s.getFullYear(),s.getMonth(),0,12)}}},{chave:"ano",rotulo:"Este ano",calcular:()=>{const s=Y();return{inicio:new Date(s.getFullYear(),0,1,12),fim:s}}}],_e=s=>{var u;const r=(u=ve.find(m=>m.chave===s))!=null?u:ve[1],{inicio:o,fim:n}=r.calcular();return{inicio:te(o),fim:te(n),preset:r.chave}};function gt({valor:s,onChange:r}){var D;const[o,n]=d.useState(!1),[u,m]=d.useState(!1),[c,p]=d.useState(),a=d.useMemo(()=>{const N=s.preset?ve.find(l=>l.chave===s.preset):null;return N?{titulo:N.rotulo,detalhe:Ne(s.inicio,s.fim)}:{titulo:Ne(s.inicio,s.fim),detalhe:null}},[s]),w=()=>{n(!1),m(!1),p(void 0)},I=()=>{var l;if(!(c!=null&&c.from))return;const N=(l=c.to)!=null?l:c.from;r({inicio:te(c.from),fim:te(N),preset:null}),w()};return e.jsxs(ks,{open:o,onOpenChange:N=>N?n(!0):w(),children:[e.jsx(Ss,{asChild:!0,children:e.jsxs("button",{className:S("flex items-center gap-2 rounded-[var(--radius-md)] border border-[var(--n200)]","bg-[var(--bg-3)] px-3 py-2 text-xs font-medium text-[var(--text-1)]","hover:bg-[var(--surface-hover)]"),children:[e.jsx(Us,{className:"h-3.5 w-3.5 text-[var(--text-3)]"}),e.jsx("span",{children:a.titulo}),a.detalhe&&e.jsx("span",{className:"font-normal text-[var(--text-3)]",children:a.detalhe}),e.jsx(ke,{className:"h-3.5 w-3.5 text-[var(--text-3)]"})]})}),e.jsx($s,{align:"end",className:"w-auto p-0",children:u?e.jsxs("div",{className:"p-3",children:[e.jsx(Ds,{mode:"range",locale:Ms,numberOfMonths:2,defaultMonth:new Date(s.inicio+"T12:00:00"),selected:c,onSelect:p,disabled:{after:Y()}}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 border-t border-[var(--n200)] pt-2",children:[e.jsx("span",{className:"text-[11px] text-[var(--text-3)]",children:c!=null&&c.from?Ne(te(c.from),te((D=c.to)!=null?D:c.from)):"Escolha a data inicial"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>m(!1),className:"rounded-[var(--radius-sm)] px-2.5 py-1 text-[11px] font-medium text-[var(--text-2)] hover:bg-[var(--surface-hover)]",children:"Voltar"}),e.jsx("button",{onClick:I,disabled:!(c!=null&&c.from),className:"rounded-[var(--radius-sm)] bg-[var(--brand)] px-2.5 py-1 text-[11px] font-medium text-white hover:bg-[var(--brand-dark)] disabled:opacity-40",children:"Aplicar"})]})]})]}):e.jsxs("div",{className:"min-w-[220px] py-1",children:[ve.map((N,l)=>{const b=s.preset===N.chave;return e.jsxs("div",{children:[(l===3||l===5)&&e.jsx("div",{className:"my-1 h-px bg-[var(--n200)]"}),e.jsxs("button",{onClick:()=>{r(_e(N.chave)),w()},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs text-[var(--text-1)] hover:bg-[var(--surface-hover)]",children:[e.jsx(es,{className:S("h-3.5 w-3.5 shrink-0",b?"text-[var(--brand)]":"invisible")}),N.rotulo]})]},N.chave)}),e.jsx("div",{className:"my-1 h-px bg-[var(--n200)]"}),e.jsxs("button",{onClick:()=>{p({from:new Date(s.inicio+"T12:00:00"),to:new Date(s.fim+"T12:00:00")}),m(!0)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs text-[var(--text-1)] hover:bg-[var(--surface-hover)]",children:[e.jsx(es,{className:S("h-3.5 w-3.5 shrink-0",s.preset?"invisible":"text-[var(--brand)]")}),"Intervalo personalizado…"]})]})})]})}const se=s=>new Intl.NumberFormat("pt-BR",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:4}).format(s),pe=1e5,ls=s=>{const r=Number(s.replace(",","."));return Number.isFinite(r)&&r>0?r:null};function bt({grupo:s}){const r=s.modelos.map(m=>m.nome),o=r.slice(0,3).join(", "),n=Math.max(0,r.length-3),u=s.modelos.filter(m=>m.tipo_modelo==="texto"&&!m.disponivel_hub).length;return e.jsxs("p",{className:"mt-1 text-[12px] leading-5 text-[var(--text-3)]",children:[o||"Nenhum modelo ativo nesta categoria",n>0?` e mais ${n}`:"",u>0?` · ${u} fora do Hub`:""]})}function ft({modelos:s,onAlterar:r}
1){const[o,n]=d.useState(null),u=d.useMemo(()=>s.filter(c=>c.tipo_modelo==="texto"),[s]);if(!u.length)return null;const m=u.filter(c=>c.disponivel_hub).length;return e.jsxs("div",{className:"mt-8 border-t border-[var(--n200)] pt-6",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-[var(--text-1)]",children:"Modelos disponíveis no Hub"}),e.jsx("p",{className:"mt-1 text-[13px] leading-5 text-[var(--text-3)]",children:"Escolha quais modelos aparecem no seletor do Hub Multimodelo para as pessoas deste ambiente. Desligar aqui não desativa o modelo: agentes, aplicações e o chat institucional continuam usando normalmente."}),e.jsxs("p",{className:"mt-1 text-[12px] text-[var(--text-3)]",children:[m," de ",u.length," disponíveis · geração de imagem é catálogo do produto e não entra nesta lista."]}),e.jsx("div",{className:"mt-4 divide-y divide-[var(--n200)] rounded-lg border border-[var(--n200)]",children:u.map(c=>e.jsxs("label",{className:"flex cursor-pointer items-center justify-between gap-3 px-4 py-3",children:[e.jsx("span",{className:"text-[13px] text-[var(--text-1)]",children:c.nome}),e.jsx("input",{type:"checkbox",className:"h-4 w-4 accent-[var(--brand)]",checked:c.disponivel_hub,disabled:o===c.id,onChange:async p=>{n(c.id);try{await r(c.id,p.target.checked)}finally{n(null)}}})]},c.id))})]})}function jt(){const[s,r]=d.useState(!1),[o,n]=d.useState(null),[u,m]=d.useState(null),[c,p]=d.useState(null),[a,w]=d.useState({}),[I,D]=d.useState([]),[N,l]=d.useState(""),[b,y]=d.useState(""),[C,_]=d.useState(""),[f,L]=d.useState("10"),E=d.useCallback(i=>{p(i),w(Object.fromEntries(i.grupos.map(h=>[h.codigo,h.padrao?String(h.padrao.limite_usd):""]))),_(h=>{var A;return h||((A=i.grupos[0])==null?void 0:A.codigo)||""})},[]),$=d.useCallback(async(i,h)=>{var A,k;try{await Ys(i,h),p(T=>T&&{...T,grupos:T.grupos.map(H=>({...H,modelos:H.modelos.map(re=>re.id===i?{...re,disponivel_hub:h}:re)}))}),B.success(h?"Modelo disponível no Hub":"Modelo removido do Hub")}catch(T){const H=(k=(A=T==null?void 0:T.response)==null?void 0:A.data)==null?void 0:k.detail;B.error(H!=null?H:"Não foi possível salvar a disponibilidade.")}},[]),Q=d.useCallback(async()=>{r(!0),m(null);try{const[i,h]=await Promise.all([he(),ts()]);E(i),D(h)}catch{m("Não foi possível carregar os limites mensais deste ambiente.")}finally{r(!1)}},[E]);d.useEffect(()=>{Q()},[Q]),d.useEffect(()=>{const i=window.setTimeout(()=>{ts(N).then(D).catch(()=>{})},250);return()=>window.clearTimeout(i)},[N]);const K=d.useMemo(()=>{var i;return(i=c==null?void 0:c.grupos.find(h=>h.codigo===C))!=null?i:null},[c,C]),q=async i=>{var A;const h=ls((A=a[i.codigo])!=null?A:"");if(h===null){B.error("Informe um valor em dólar maior que zero.");return}if(h>pe){B.error(`O limite máximo é ${se(pe)} por mês.`);return}n(`padrao:${i.codigo}`);try{await Qs(i.codigo,h),E(await he()),B.success("Limite mensal padrão atualizado",{description:`Cada usuário terá ${se(h)} por mês nessa categoria.`})}catch(k){B.error("Não foi possível salvar o limite mensal padrão.",{description:Ze(k)})}finally{n(null)}},G=async()=>{const i=ls(f);if(!b||!C||i===null){B.error("Escolha o usuário, a categoria e informe um valor válido.");return}if(i>pe){B.error(`O limite máximo é ${se(pe)} por mês.`);return}n("excecao");try{await Ks(b,C,i),E(await he()),y(""),B.success("Exceção individual salva",{description:"Este valor substitui o padrão somente para o usuário escolhido."})}catch(h){B.error("Não foi possível salvar a exceção individual.",{description:Ze(h)})}finally{n(null)}},ce=async(i,h)=>{n(`remover:${i}:${h}`);try{await Ws(i,h),E(await he()),B.success("Exceção removida",{description:"O usuário voltou a usar o limite mensal padrão do ambiente."})}catch{B.error("Não foi possível remover a exceção.")}finally{n(null)}};return e.jsx(U,{children:e.jsx(z,{className:"p-4 md:p-6",children:s?e.jsxs("div",{className:"flex min-h-48 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ue,{className:"h-4 w-4 animate-spin"})," Carregando limites…"]}):u?e.jsxs("div",{className:"flex min-h-48 flex-col items-center justify-center gap-3 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:u}),e.jsx(me,{variant:"outline",size:"sm",onClick:Q,children:"Tentar novamente"})]}):c!=null&&c.grupos.length?e.jsxs("div",{className:"space-y-7",children:[e.jsxs("section",{"aria-labelledby":"padrao-ambiente-titulo",className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"padrao-ambiente-titulo",className:"text-sm font-semibold text-[var(--text-1)]",children:"Padrão do ambiente"}),e.jsx("p",{className:"mt-0.5 text-xs text-[var(--text-3)]",children:"Alterar aqui atualiza o próximo saldo de todos, sem somar o consumo entre usuários."})]}),e.jsx("div",{className:"space-y-3",children:c.grupos.map(i=>{var h;return e.jsxs("div",{className:"rounded-lg border border-[var(--n200)] bg-[var(--bg-3)] p-4",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-[var(--text-1)]",children:i.nome}),e.jsx("p",{className:"mt-0.5 text-xs leading-5 text-[var(--text-2)]",children:i.descricao||"Modelos que compartilham o mesmo limite mensal por usuário."}),e.jsx(bt,{grupo:i})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-end gap-2",children:[e.jsxs("div",{className:"w-40",children:[e.jsx(xe,{htmlFor:`padrao-${i.codigo}`,className:"text-[11px] text-[var(--text-3)]",children:"Dólares por usuário"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground",children:"US$"}),e.jsx(We,{id:`padrao-${i.codigo}
1`,inputMode:"decimal",value:(h=a[i.codigo])!=null?h:"",onChange:A=>w(k=>({...k,[i.codigo]:A.target.value})),placeholder:"10,00",className:"pl-10 tabular-nums"})]})]}),e.jsxs(me,{onClick:()=>q(i),disabled:o!==null,children:[o===`padrao:${i.codigo}`&&e.jsx(ue,{className:"mr-2 h-4 w-4 animate-spin"}),"Salvar padrão"]})]})]}),i.padrao&&e.jsxs("p",{className:"mt-3 text-[11px] text-[var(--text-3)]",children:["Atual: ",se(i.padrao.limite_usd)," por usuário · uso mensal"]})]},i.codigo)})})]}),e.jsxs("section",{"aria-labelledby":"excecoes-titulo",className:"space-y-3 border-t border-[var(--n200)] pt-6",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"excecoes-titulo",className:"text-sm font-semibold text-[var(--text-1)]",children:"Exceções individuais"}),e.jsx("p",{className:"mt-0.5 text-xs text-[var(--text-3)]",children:"Use apenas quando uma pessoa precisar de um valor diferente do padrão."})]}),e.jsxs("div",{className:"rounded-lg border border-[var(--brand-20)] bg-[var(--brand-10)] p-4",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(220px,1fr)_minmax(180px,0.8fr)_150px_auto] md:items-end",children:[e.jsxs("div",{children:[e.jsx(xe,{children:"Usuário"}),e.jsx("div",{className:"mt-1",children:e.jsx(Je,{items:I,value:b,onChange:i=>y(i),getItemId:i=>i.id,getItemLabel:i=>i.nome,getItemDescription:i=>i.email,isMultiple:!1,icon:ss,entityName:"usuário",entityNamePlural:"usuários",placeholder:"Escolha um usuário",searchPlaceholder:"Buscar por nome ou e-mail",serverSearch:!0,searchValue:N,onSearch:l,showSelectedTags:!1,triggerClassName:"h-10 w-full"})})]}),e.jsxs("div",{children:[e.jsx(xe,{children:"Categoria"}),e.jsx("div",{className:"mt-1",children:e.jsx(Je,{items:c.grupos,value:C,onChange:i=>_(i),getItemId:i=>i.codigo,getItemLabel:i=>i.nome,getItemDescription:i=>{var h;return(h=i.descricao)!=null?h:void 0},isMultiple:!1,entityName:"categoria",entityNamePlural:"categorias",placeholder:"Escolha a categoria",showSelectedTags:!1,triggerClassName:"h-10 w-full"})})]}),e.jsxs("div",{children:[e.jsx(xe,{htmlFor:"valor-excecao",children:"Dólares por mês"}),e.jsx(We,{id:"valor-excecao",inputMode:"decimal",value:f,onChange:i=>L(i.target.value),className:"mt-1 tabular-nums"})]}),e.jsxs(me,{onClick:G,disabled:o!==null,children:[o==="excecao"&&e.jsx(ue,{className:"mr-2 h-4 w-4 animate-spin"}),"Salvar exceção"]})]}),(K==null?void 0:K.padrao)&&e.jsxs("p",{className:"mt-3 text-[11px] text-[var(--text-2)]",children:["Sem exceção, esta categoria usa ",se(K.padrao.limite_usd)," por usuário."]})]}),c.excecoes.length===0?e.jsx("p",{className:"rounded-lg border border-dashed border-[var(--n200)] px-4 py-5 text-center text-sm text-muted-foreground",children:"Nenhuma exceção cadastrada. Todos usam o padrão do ambiente."}):e.jsx("div",{className:"divide-y divide-[var(--n200)] rounded-lg border border-[var(--n200)]",children:c.excecoes.map(i=>{var k;const h=c.grupos.find(T=>T.codigo===i.grupo_modelo),A=o===`remover:${i.usuario.id}:${i.grupo_modelo}`;return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 px-4 py-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-[var(--n100)] text-[var(--n600)]",children:e.jsx(ss,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--text-1)]",children:i.usuario.nome}),e.jsxs("p",{className:"truncate text-xs text-[var(--text-3)]",children:[i.usuario.email," · ",(k=h==null?void 0:h.nome)!=null?k:i.grupo_modelo]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-semibold tabular-nums text-[var(--text-1)]",children:se(i.limite_usd)}),e.jsxs(me,{variant:"ghost",size:"sm",disabled:o!==null,onClick:()=>ce(i.usuario.id,i.grupo_modelo),children:[A&&e.jsx(ue,{className:"mr-2 h-4 w-4 animate-spin"}),"Voltar ao padrão"]})]})]},i.id)})})]}),e.jsx(ft,{modelos:c.grupos.flatMap(i=>i.modelos),onAlterar:$})]}):e.jsx("p",{className:"py-12 text-center text-sm text-muted-foreground",children:"Nenhuma categoria de modelos está configurada com limite mensal."})})})}const V=s=>s.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim();function we({valor:s,onChange:r,placeholder:o}){return e.jsxs("div",{className:"relative w-full max-w-xs",children:[e.jsx(zs,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--text-3)]"}),e.jsx("input",{value:s,onChange:n=>r(n.target.value),placeholder:o,className:S("h-8 w-full rounded-[var(--radius-md)] border border-[var(--n200)] bg-[var(--bg-3)]","pl-8 pr-7 text-xs text-[var(--text-1)] placeholder:text-[var(--text-4)]","focus:border-[var(--brand)] focus:outline-none focus:ring-2 focus:ring-[var(--brand-10)]")}),s&&e.jsx("button",{onClick:()=>r(""),"aria-label":"Limpar busca",className:"absolute right-1.5 top-1/2 flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-[var(--text-3)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-1)]",children:e.jsx(ms,{className:"h-3 w-3"})})]})}
1function vs(s,r){const[o,n]=d.useState(0),u=Math.max(1,Math.ceil(s.length/r));d.useEffect(()=>{n(p=>Math.min(p,u-1))},[u]);const m=o*r;return{visiveis:d.useMemo(()=>s.slice(m,m+r),[s,m,r]),pagina:o,paginas:u,inicio:m,fim:Math.min(m+r,s.length),total:s.length,irPara:n,reiniciar:()=>n(0)}}function gs({inicio:s,fim:r,total:o,pagina:n,paginas:u,irPara:m,unidade:c}){return u<=1?null:e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-xs text-[var(--text-3)]",children:[e.jsxs("span",{className:"tabular-nums",children:[s+1,"–",r," de ",o," ",c]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>m(Math.max(0,n-1)),disabled:n===0,"aria-label":"Página anterior",className:"flex h-8 w-8 items-center justify-center rounded-[var(--radius-md)] border border-[var(--n200)] text-[var(--text-2)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-1)] disabled:opacity-40 disabled:hover:bg-transparent",children:e.jsx(Hs,{className:"h-4 w-4"})}),e.jsxs("span",{className:"min-w-[3.5rem] text-center tabular-nums text-[var(--text-2)]",children:[n+1," de ",u]}),e.jsx("button",{onClick:()=>m(Math.min(u-1,n+1)),disabled:n>=u-1,"aria-label":"Próxima página",className:"flex h-8 w-8 items-center justify-center rounded-[var(--radius-md)] border border-[var(--n200)] text-[var(--text-2)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-1)] disabled:opacity-40 disabled:hover:bg-transparent",children:e.jsx(Vs,{className:"h-4 w-4"})})]})]})}function Ce({termo:s}){return e.jsxs("p",{className:"px-1 py-6 text-sm text-[var(--text-3)]",children:["Nada encontrado para “",e.jsx("strong",{className:"text-[var(--text-2)]",children:s}),"”."]})}const Nt=s=>{const r=new Date(s.inicio+"T12:00:00"),o=new Date(s.fim+"T12:00:00");return Math.round((o.getTime()-r.getTime())/864e5)+1};function le({descricao:s,soma:r,total:o,restante:n}){const u=o>0?r/o*100:0,m=u>=99.5;return e.jsxs("p",{className:"mb-3 text-sm text-[var(--text-2)]",children:[s," somam"," ",e.jsx("strong",{className:"tabular-nums font-semibold text-[var(--text-1)]",children:g(r)})," —"," ",m?e.jsx(e.Fragment,{children:"todo o custo do período."}):e.jsxs(e.Fragment,{children:[e.jsxs("strong",{className:"tabular-nums text-[var(--text-1)]",children:[u.toFixed(0),"%"]})," do custo do período",n?`. ${n}`:"."]})]})}function cs(s){var o;const r=new Map;for(const n of s){const u=(o=r.get(n.nome))!=null?o:{nome:n.nome,chamadas:0,custo_usd:0,cadastros:0};u.chamadas+=Number(n.chamadas)||0,u.custo_usd+=Number(n.custo_usd)||0,u.cadastros+=1,r.set(n.nome,u)}return Array.from(r.values()).sort((n,u)=>u.custo_usd-n.custo_usd)}const bs=8,yt=(s,r)=>{var n;return r===1?s:(n={requisição:"requisições","requisição básica":"requisições básicas","requisição avançada":"requisições avançadas",minuto:"minutos"}[s])!=null?n:s};function ds({itens:s,rotuloChave:r,placeholderBusca:o}){const[n,u]=d.useState(""),m=Math.max(1,...s.map(a=>Number(a.custo_usd)||0)),c=d.useMemo(()=>{const a=V(n);return a?s.filter(w=>V(w.nome).includes(a)):s},[s,n]),p=vs(c,bs);return s.length===0?e.jsx("p",{className:"px-1 py-6 text-sm text-muted-foreground",children:"sem custo neste período."}):e.jsxs("div",{children:[e.jsx("div",{className:"mb-3",children:e.jsx(we,{valor:n,onChange:u,placeholder:o})}),c.length===0&&e.jsx(Ce,{termo:n}),e.jsx("div",{className:S("overflow-x-auto",c.length===0&&"hidden"),children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-[11px] uppercase tracking-wider text-muted-foreground",children:[e.jsx("th",{className:"py-2 pr-4 text-left font-medium",children:r}),e.jsx("th",{className:"py-2 pr-4 text-right font-medium",children:"chamadas"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"custo"})]})}),e.jsx("tbody",{children:p.visiveis.map((a,w)=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsxs("td",{className:"max-w-[380px] py-2 pr-4",children:[e.jsx("span",{className:"align-middle",children:a.nome}),a.sub&&e.jsx("span",{className:"ml-2 text-[11px] text-muted-foreground",children:a.sub}
1),a.tag&&e.jsx("span",{className:"ml-2 rounded-full bg-[var(--bg-2)] px-2 py-0.5 align-middle text-[10px] font-medium uppercase tracking-wider text-[var(--text-3)]",children:a.tag})]}),e.jsx("td",{className:"py-2 pr-4 text-right tabular-nums text-muted-foreground",children:M(a.chamadas)}),e.jsx("td",{className:"py-2 text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("span",{className:"h-1.5 rounded-full bg-[var(--brand)]/70",style:{width:`${Number(a.custo_usd)/m*56+4}px`}}),e.jsx("span",{className:"tabular-nums font-medium",children:g(a.custo_usd)})]})})]},p.inicio+w))})]})}),e.jsx(gs,{...p,unidade:r+"s"})]})}function It(){var Me,Ae,Fe,Ee,Te,Oe,Pe,Ie,Le,qe,Be,Re,Ue,ze,He,Ve,Ge,Xe,Ye,Qe,Ke;const{hasPermission:s}=As(),[r,o]=d.useState("visao"),[n,u]=d.useState(!1),[m,c]=d.useState(()=>_e("30d")),p=Nt(m),[a,w]=d.useState(null),[I,D]=d.useState(!0),[N,l]=d.useState(null),[b,y]=d.useState("modelos"),[C,_]=d.useState(!1),[f,L]=d.useState(null);d.useEffect(()=>{let t=!0;return s("uso_gerenciar").then(x=>{t&&u(x)}),()=>{t=!1}},[s]);const E=d.useCallback(async()=>{D(!0),l(null);try{w(await us(p,50,"todos",f,m))}catch{l("Não foi possível carregar os custos neste período.")}finally{D(!1)}},[m.inicio,m.fim,p,f]);d.useEffect(()=>{E()},[E]);const[$,Q]=d.useState([]);d.useEffect(()=>{var x;const t=((x=a==null?void 0:a.por_origem)!=null?x:[]).filter(j=>!j.pai).filter(j=>j.origem!=="Outros usos do ambiente"||!j.sem_consumo).map(j=>({origem:j.origem,semConsumo:!!j.sem_consumo}));t.length>0&&Q(t)},[a]);const K=d.useMemo(()=>[{valor:null,rotulo:"Todas"},...$.map(t=>({valor:t.origem,rotulo:t.origem,titulo:t.semConsumo?"Sem uso neste período":void 0}))],[$]),q=Number((Me=a==null?void 0:a.totais)==null?void 0:Me.custo_usd)||0,G=d.useMemo(()=>{var R,P;const t=((R=a==null?void 0:a.por_origem)!=null?R:[]).filter(J=>!J.pai&&!J.sem_consumo),x=f?t.find(J=>J.origem===f):t[0],j=Number(x==null?void 0:x.custo_medio_unidade)||0,v=((P=a==null?void 0:a.por_conversa)!=null?P:[])[0];if(!v||!j||!x)return null;const O=Number(v.custo_usd)/j;return O>=5?{...v,vezes:O,base:x.origem}:null},[a,f]),ce=Number((Ae=a==null?void 0:a.atribuicao_agente)==null?void 0:Ae.com_agente)||0,i=Number((Fe=a==null?void 0:a.atribuicao_agente)==null?void 0:Fe.sem_agente)||0,h=d.useMemo(()=>{var x,j;const t=new Map;for(const v of(x=a==null?void 0:a.por_modelo)!=null?x:[]){const O=xs(v.modelo),R=Number(v.chamadas)||0,P=(j=t.get(O))!=null?j:{nome:O,ids:[],chamadas:0,tokens_entrada:0,tokens_saida:0,custo_usd:0,latenciaXchamadas:0,tipo:null};P.ids.push(v.modelo),P.chamadas+=R,P.tokens_entrada+=Number(v.tokens_entrada)||0,P.tokens_saida+=Number(v.tokens_saida)||0,P.custo_usd+=Number(v.custo_usd)||0,P.latenciaXchamadas+=(Number(v.latencia_media_ms)||0)*R,v.tipo==="imagem"&&(P.tipo="imagem"),t.set(O,P)}return Array.from(t.values()).map(v=>({...v,latencia_media_ms:v.chamadas>0?v.latenciaXchamadas/v.chamadas:0,custo_por_chamada:v.chamadas>0?v.custo_usd/v.chamadas:0,provedor:Js(v.ids[0])})).sort((v,O)=>O.custo_usd-v.custo_usd)},[a]),A=d.useMemo(()=>{var O,R,P,J;const t=F=>V(F)==="aluno sem cadastro",x=[...cs(((O=a==null?void 0:a.por_aluno)!=null?O:[]).map(F=>t(F.nome)?{...F,nome:"Não identificada"}:F)).map(F=>({...F,tipo:F.nome==="Não identificada"?"Não identificada":"Aluno"})),...cs((R=a==null?void 0:a.por_funcionario)!=null?R:[]).map(F=>({...F,tipo:"Funcionário"}))],j=Number((P=a==null?void 0:a.atribuicao)==null?void 0:P.custo_anonimo)||0,v=Number((J=a==null?void 0:a.atribuicao)==null?void 0:J.chamadas_anonimo)||0;if(j>0||v>0){const F=x.find(fe=>fe.tipo==="Não identificada");F?(F.chamadas+=v,F.custo_usd+=j):x.push({nome:"Não identificada",chamadas:v,custo_usd:j,cadastros:1,tipo:"Não identificada"})}return x.sort((F,fe)=>fe.custo_usd-F.custo_usd)},[a]),k=h.reduce((t,x)=>t+x.custo_usd,0),T=(Ee=a==null?void 0:a.servicos_auxiliares)!=null?Ee:[],H=T.reduce((t,x)=>t+(Number(x.custo_usd)||0),0),re=.01,{relevantes:Se,cauda:oe}=d.useMemo(()=>{const t=[],x=[];for(const j of h)((k>0?j.custo_usd/k:0)>=re?t:x).push(j);return x.length>1?{relevantes:t,cauda:x}:{relevantes:h,cauda:[]}}
1,[h,k]),[$e,fs]=d.useState(!1),[ne,js]=d.useState(""),[Z,Ns]=d.useState(""),ge=d.useMemo(()=>{const t=V(ne);return t?h.filter(x=>{var j;return V(x.nome).includes(t)||V((j=x.provedor)!=null?j:"").includes(t)||x.ids.some(v=>V(v).includes(t))}):Se},[ne,Se,h]),be=d.useMemo(()=>{var j;const t=(j=a==null?void 0:a.por_agente)!=null?j:[],x=V(Z);return x?t.filter(v=>{var O,R;return V((O=v.agente)!=null?O:"").includes(x)||V((R=v.fluxo)!=null?R:"").includes(x)}):t},[a,Z]),De=vs(be,bs),ys=oe.reduce((t,x)=>t+x.custo_usd,0),_s=oe.reduce((t,x)=>t+x.chamadas,0),W=d.useMemo(()=>{const t=[];let x=0;for(const j of h)if(t.push(j),x+=j.custo_usd,k>0&&x/k>=.9)break;return{lista:t,pct:k>0?x/k*100:0}},[h,k]),ws=!!f&&!!a&&q===0,de=((Te=a==null?void 0:a.por_origem)!=null?Te:[]).find(t=>t.origem===f&&!t.pai);return e.jsxs("div",{className:"space-y-4 p-4 md:p-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(Fs,{title:"Consumo do Ambiente",subtitle:r==="limites"?"Defina o limite mensal padrão do ambiente e as exceções individuais dos usuários.":"Quanto o ambiente gasta, por onde o custo nasce e para quem ele vai — em dólar, no período.",actions:r==="visao"?e.jsx(gt,{valor:m,onChange:c}):void 0}),n&&e.jsxs("div",{role:"tablist","aria-label":"Seções do consumo do ambiente",className:"inline-flex w-fit rounded-lg border border-[var(--n200)] bg-[var(--bg-2)] p-1",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":r==="visao",onClick:()=>o("visao"),className:S("rounded-md px-3 py-1.5 text-xs font-medium transition-colors",r==="visao"?"bg-[var(--white)] text-[var(--text-1)] shadow-sm":"text-[var(--text-3)] hover:text-[var(--text-1)]"),children:"Visão geral"}),e.jsx("button",{type:"button",role:"tab","aria-selected":r==="limites",onClick:()=>o("limites"),className:S("rounded-md px-3 py-1.5 text-xs font-medium transition-colors",r==="limites"?"bg-[var(--white)] text-[var(--text-1)] shadow-sm":"text-[var(--text-3)] hover:text-[var(--text-1)]"),children:"Limites de uso"})]}),r==="visao"&&$.length>1&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase tracking-wider text-[var(--text-3)]",children:"Origem"}),e.jsx(ps,{aria:"Origem do consumo",valor:f,onChange:t=>L(t),opcoes:K})]})]}),r==="limites"&&n?e.jsx(jt,{}):N?e.jsx(U,{children:e.jsxs(z,{className:"flex items-center justify-between gap-3 p-6 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:N}),e.jsx("button",{onClick:E,className:"rounded-md border px-3 py-1.5 text-xs font-medium hover:bg-muted",children:"Tentar de novo"})]})}):I||!a?e.jsx("div",{className:"grid gap-3 md:grid-cols-4",children:[0,1,2,3].map(t=>e.jsx(Es,{className:"h-24"},t))}):e.jsxs(e.Fragment,{children:[((Pe=(Oe=a.cobertura)==null?void 0:Oe.modelos_sem_preco)==null?void 0:Pe.length)>0&&e.jsx(xt,{cobertura:a.cobertura}),ws?e.jsx(U,{children:e.jsxs(z,{className:"flex flex-col items-center gap-1 px-6 py-12 text-center",children:[e.jsxs("p",{className:"text-sm font-medium text-[var(--text-1)]",children:[f," não teve consumo nos últimos ",p," dias."]}),e.jsx("p",{className:"max-w-md text-sm text-[var(--text-2)]",children:de!=null&&de.aplicacoes_cadastradas?`${M(de.aplicacoes_cadastradas)} aplicação(ões) cadastrada(s), nenhuma usada no período.`:"Nenhum uso registrado nesta origem no período."}),e.jsxs("div",{className:"mt-4 flex flex-wrap justify-center gap-2",children:[p<90&&e.jsx("button",{onClick:()=>c(_e("90d")),className:"rounded-[var(--radius-md)] bg-[var(--brand)] px-3 py-1.5 text-xs font-medium text-white hover:bg-[var(--brand-dark)]",children:"Procurar em 90 dias"}),e.jsx("button",{onClick:()=>L(null),className:"rounded-[var(--radius-md)] border border-[var(--n300)] px-3 py-1.5 text-xs font-medium text-[var(--text-2)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-1)]",children:"Ver todas as origens"})]})]})}):e.jsxs(e.Fragment,{children:[e.jsx(U,{className:"border-[var(--brand-20)] bg-[var(--brand-10)]",children:e.jsxs(z,{className:"flex flex-wrap items-end justify-between gap-x-8 gap-y-3 p-4 md:px-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-[var(--brand)]",children:f?`Custo de ${f} no período`:"Custo total do período"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[e.jsx("span",{className:"text-3xl font-semibold leading-none tracking-tight tabular-nums text-[var(--text-1)]",children:(Le=(Ie=X(q,a.cambio))==null?void 0:Ie.replace("≈ ",""))!=null?Le:g(q)}
1),X(q,a.cambio)&&e.jsx("span",{className:"text-sm tabular-nums text-[var(--text-2)]",children:g(q)}),((qe=a.comparativo)==null?void 0:qe.variacao_pct)!=null&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-[var(--bg-3)] px-2 py-0.5 text-[11px] font-medium tabular-nums text-[var(--text-2)]",children:[Number((Be=a.comparativo)==null?void 0:Be.variacao_pct)>=0?e.jsx(Gs,{className:"h-3 w-3"}):e.jsx(Xs,{className:"h-3 w-3"}),Number((Re=a.comparativo)==null?void 0:Re.variacao_pct)>=0?"+":"",(Ue=a.comparativo)==null?void 0:Ue.variacao_pct,"% vs. ",p," dias anteriores"]}),as(a.cambio)&&e.jsx("span",{className:"inline-flex items-center gap-1 rounded-full border border-[var(--brand-20)] bg-[var(--bg-3)] px-2 py-0.5 text-[11px] font-medium tabular-nums text-[var(--text-2)]",title:(ze=je(a.cambio))!=null?ze:void 0,children:as(a.cambio)})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-6 gap-y-1 text-xs text-[var(--text-2)]",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"font-semibold text-[var(--text-1)]",children:M(a.totais.conversas)})," ","conversas"]}),e.jsxs("span",{children:[e.jsx("strong",{className:"font-semibold text-[var(--text-1)]",children:M(a.totais.chamadas)})," ","chamadas"]}),e.jsxs("span",{children:[e.jsx("strong",{className:"font-semibold text-[var(--text-1)]",children:ae(Number(a.totais.tokens_entrada)+Number(a.totais.tokens_saida))})," ","tokens"]})]})]})}),e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-xs font-medium uppercase tracking-wider text-[var(--text-3)]",children:f?`Dentro de ${f}`:"Onde o custo nasce"}),e.jsx(mt,{origens:(He=a.por_origem)!=null?He:[],cambio:a.cambio,selecionada:f,onSelecionar:L})]}),G&&e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-xs font-medium uppercase tracking-wider text-[var(--text-3)]",children:"Onde dá para mexer"}),e.jsx(U,{className:"border-[var(--brand-20)]",children:e.jsxs(z,{className:"flex flex-wrap items-center justify-between gap-3 p-4",children:[e.jsxs("p",{className:"text-sm text-[var(--text-2)]",children:["Uma conversa custou"," ",e.jsx("strong",{className:"tabular-nums text-[var(--text-1)]",children:g(G.custo_usd)})," ","— ",e.jsxs("strong",{className:"text-[var(--text-1)]",children:[Math.round(G.vezes),"×"]})," ","a média de ",G.base,".",e.jsxs("span",{className:"ml-1.5 text-[var(--text-3)]",children:["“",G.titulo,"”"]})]}),e.jsxs(Ts,{open:C,onOpenChange:_,children:[e.jsx(Os,{asChild:!0,children:e.jsx("button",{className:"shrink-0 rounded-[var(--radius-md)] border border-[var(--n300)] px-3 py-1.5 text-xs font-medium hover:bg-[var(--surface-hover)]",children:"Ver por que custou isso"})}),e.jsxs(Ps,{className:"max-w-5xl",children:[e.jsx(Is,{children:e.jsxs(Ls,{className:"text-sm",children:["Passo a passo — “",G.titulo,"”"]})}),e.jsx("div",{className:"max-h-[70vh] overflow-y-auto",children:e.jsx(rs,{dias:p,chatId:G.chat_id})})]})]})]})})]}),e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-xs font-medium uppercase tracking-wider text-[var(--text-3)]",children:"Como evoluiu"}),e.jsx(U,{children:e.jsx(z,{className:"p-4 md:p-5",children:e.jsx(vt,{serie:a.serie,dias:p,periodo:m,origem:f,opcoesOrigem:K})})})]}),e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-xs font-medium uppercase tracking-wider text-[var(--text-3)]",children:"Onde o custo está concentrado"}),e.jsx(U,{children:e.jsxs(z,{className:"p-4 md:p-5",children:[f&&e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-[11px] text-[var(--text-2)]",children:["Recorte aplicado a todas as abas:",e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-[var(--brand-10)] px-2.5 py-1 font-medium text-[var(--brand-600)]",children:[f,e.jsx("button",{onClick:()=>L(null),"aria-label":"Limpar recorte",className:"rounded-full hover:bg-[var(--brand-20)]",children:e.jsx(ms,{className:"h-3 w-3"})})]})]}),e.jsxs(qs,{value:b,onValueChange:y,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs(Bs,{className:"h-auto flex-wrap justify-start",children:[e.jsx(ie,{value:"modelos",children:"Modelos"}),e.jsx(ie,{value:"servicos",children:"Outros recursos"}),e.jsx(ie,{value:"agentes",children:"Agentes"}),e.jsx(ie,{value:"pessoas",children:"Pessoas"}),e.jsx(ie,{value:"conversas",children:"Conversas"})]}),e.jsx("button",{onClick:()=>y(b==="rastreio"?"modelos":"rastreio"),className:S("text-[11px] underline underline-offset-2",b==="rastreio"?"font-medium text-[var(--text-1)]":"text-[var(--text-3)] hover:text-[var(--text-1)]"),children:b==="rastreio"?"← voltar aos eixos":"Rastreio técnico →"})]}),e.jsxs(ee,{value:"modelos",className:"mt-4",children:[W.lista.length>0&&k>0?e.jsxs("p",{className:"mb-3 text-sm text-[var(--text-2)]",children:[e.jsx("strong",{className:"font-semibold text-[var(--text-1)]",children:W.lista.map(t=>t.nome).join(" e ")})," ",W.lista.length===1?"responde":"respondem"," por"," ",e.jsxs("strong",{className:"tabular-nums text-[var(--text-1)]",children:[W.pct.toFixed(0),"%"]})," ","do custo",h.length>W.lista.length&&e.jsxs(e.Fragment,{children:[". Os outros ",h.length-W.lista.length," somam"," ",e.jsx("span",{className:"tabular-nums",children:g(k-W.lista.reduce((t,x)=>t+x.custo_usd,0))})]}),"."]}):e.jsx(le,{descricao:`Os ${h.length} modelos em uso`,soma:k,total:q,restante:H>0?`Outros recursos somam ${g(H)}; o restante são chamadas sem modelo registrado.`:"O restante são chamadas sem modelo registrado."}),e.jsx("div",{className:"mb-3",children:e.jsx(we,{valor:ne,onChange:js,placeholder:"Buscar modelo ou provedor…"})}),ge.length===0&&e.jsx(Ce,{termo:ne}),e.jsx("div",{className:S("overflow-x-auto",ge.length===0&&"hidden"),children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-[11px] uppercase tracking-wider text-[var(--text-3)]",children:[e.jsx("th",{className:"py-2 pr-4 text-left font-medium",children:"modelo"}),e.jsx("th",{className:"py-2 pr-4 text-right font-medium",children:"chamadas"}),e.jsx("th",{className:"py-2 pr-4 text-right font-medium",children:"por chamada"}),e.jsx("th",{className:"py-2 pr-4 text-left font-medium",children:"participação"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"custo"})]})}),e.jsxs("tbody",{children:[ge.map(t=>{const x=k>0?t.custo_usd/k*100:0;return e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsxs("td",{className:"py-2.5 pr-4",children:[e.jsx("div",{className:"font-medium text-[var(--text-1)]",children:t.nome}),e.jsx("div",{className:"text-[11px] text-[var(--text-3)]",children:[t.provedor,t.ids.length>1?`${t.ids.length} rotas`:null,t.latencia_media_ms>0?`${Zs(t.latencia_media_ms)} em média`:null,t.tipo==="imagem"?"cobrado por imagem, sem tokens":`${ae(t.tokens_entrada
1)} / ${ae(t.tokens_saida)} tokens`].filter(Boolean).join(" · ")})]}),e.jsx("td",{className:"py-2.5 pr-4 text-right tabular-nums text-[var(--text-2)]",children:M(t.chamadas)}),e.jsx("td",{className:"py-2.5 pr-4 text-right tabular-nums text-[var(--text-2)]",children:g(t.custo_por_chamada)}),e.jsx("td",{className:"py-2.5 pr-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-24 overflow-hidden rounded-full bg-[var(--n200)]",children:e.jsx("div",{className:"h-full rounded-full bg-[var(--brand)]",style:{width:`${Math.max(x,1)}%`}})}),e.jsx("span",{className:"tabular-nums text-[11px] text-[var(--text-2)]",children:x>=1?`${x.toFixed(0)}%`:"<1%"})]})}),e.jsx("td",{className:"py-2.5 text-right font-semibold tabular-nums text-[var(--text-1)]",children:g(t.custo_usd)})]},t.nome)}),!ne&&oe.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("tr",{className:"border-b last:border-0",children:e.jsx("td",{colSpan:5,className:"py-2",children:e.jsxs("button",{onClick:()=>fs(t=>!t),className:"flex w-full items-center gap-2 text-left text-[13px] text-[var(--text-2)] hover:text-[var(--text-1)]",children:[e.jsx(ke,{className:S("h-3.5 w-3.5 transition-transform duration-150",$e?"rotate-0":"-rotate-90")}),e.jsxs("span",{children:[oe.length," modelos abaixo de 1% ·"," ",e.jsx("span",{className:"tabular-nums",children:M(_s)})," chamadas"]}),e.jsx("span",{className:"ml-auto tabular-nums font-medium text-[var(--text-1)]",children:g(ys)})]})})}),$e&&oe.map(t=>e.jsxs("tr",{className:"border-b bg-[var(--bg-2)] text-[13px] last:border-0",children:[e.jsxs("td",{className:"py-2 pl-6 pr-4",children:[e.jsx("span",{className:"text-[var(--text-2)]",children:t.nome}),e.jsx("span",{className:"ml-2 text-[11px] text-[var(--text-3)]",children:t.provedor})]}),e.jsx("td",{className:"py-2 pr-4 text-right tabular-nums text-[var(--text-3)]",children:M(t.chamadas)}),e.jsx("td",{className:"py-2 pr-4 text-right tabular-nums text-[var(--text-3)]",children:g(t.custo_por_chamada)}),e.jsx("td",{className:"py-2 pr-4 text-[11px] text-[var(--text-3)]",children:"<1%"}),e.jsx("td",{className:"py-2 text-right tabular-nums text-[var(--text-2)]",children:g(t.custo_usd)})]},t.nome))]})]})]})})]}),e.jsxs(ee,{value:"servicos",className:"mt-4",children:[e.jsx("p",{className:"mb-3 text-sm text-[var(--text-2)]",children:"Buscas na web e transcrições entram no custo total e no limite do usuário, mas são cobradas por uso — não por token."}),T.length===0?e.jsxs("div",{className:"rounded-[var(--radius-md)] border border-dashed border-[var(--n300)] px-4 py-6",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--text-1)]",children:"Nenhum outro recurso usado neste período."}),e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-[var(--text-3)]",children:"Serper, Tavily e AWS Transcribe aparecem aqui após o primeiro uso, com a quantidade consumida e o preço aplicado naquela chamada."})]}):e.jsxs(e.Fragment,{children:[e.jsx(le,{descricao:"Os outros recursos",soma:H,total:q,restante:"O restante vem dos modelos e de outros recursos medidos."}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-[11px] uppercase tracking-wider text-[var(--text-3)]",children:[e.jsx("th",{className:"py-2 pr-4 text-left font-medium",children:"serviço"}),e.jsx("th",{className:"py-2 pr-4 text-right font-medium",children:"uso"}),e.jsx("th",{className:"py-2 pr-4 text-right font-medium",children:"preço médio unitário"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"custo"})]})}),e.jsx("tbody",{children:T.map(t=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsxs("td",{className:"py-3 pr-4",children:[e.jsx("div",{className:"font-medium text-[var(--text-1)]",children:t.servico}),e.jsx("div",{className:"text-[11px] text-[var(--text-3)]",children:t.tipo==="audio"?"Transcrição de áudio":"Pesquisa na web"})]}),e.jsx("td",{className:"py-3 pr-4 text-right tabular-nums text-[var(--text-2)]",children:`${Number(t.quantidade).toLocaleStr
1ing("pt-BR",{maximumFractionDigits:2})} ${yt(t.unidade,Number(t.quantidade))}`}),e.jsx("td",{className:"py-3 pr-4 text-right tabular-nums",children:t.preco_configurado?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-[var(--text-1)]",children:et(t.custo_unitario_usd)}),e.jsxs("span",{className:"text-[var(--text-3)]",children:["/",t.unidade]})]}):e.jsx("span",{className:"inline-flex rounded-full bg-[var(--warning-bg)] px-2 py-0.5 text-[11px] font-medium text-[var(--warning)]",children:"preço não configurado"})}),e.jsxs("td",{className:"py-3 text-right font-semibold tabular-nums text-[var(--text-1)]",children:[e.jsx("div",{children:g(t.custo_usd)}),X(t.custo_usd,a.cambio)&&e.jsx("div",{className:"text-[11px] font-normal text-[var(--text-3)]",children:X(t.custo_usd,a.cambio)})]})]},`${t.servico}-${t.unidade}`))})]})}),e.jsx("p",{className:"mt-3 text-[11px] leading-relaxed text-[var(--text-3)]",children:"O preço unitário é o valor contratual registrado no momento do uso. Quando ele não está configurado, a chamada continua medida, mas fica fora do custo monetário até a configuração do ambiente ser corrigida."})]})]}),e.jsxs(ee,{value:"agentes",className:"mt-4",children:[((Ve=a.por_agente)!=null?Ve:[]).length>0&&e.jsx(le,{descricao:`Os ${((Ge=a.por_agente)!=null?Ge:[]).length} agentes identificados`,soma:((Xe=a.por_agente)!=null?Xe:[]).reduce((t,x)=>t+(Number(x.custo_usd)||0),0),total:q,restante:"O restante é anterior à coleta por agente."}),((Ye=a.por_agente)!=null?Ye:[]).length>0&&e.jsx("div",{className:"mb-3",children:e.jsx(we,{valor:Z,onChange:Ns,placeholder:"Buscar agente ou fluxo…"})}),be.length===0&&Z&&e.jsx(Ce,{termo:Z}),e.jsx("div",{className:S("overflow-x-auto",be.length===0&&Z&&"hidden"),children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-[11px] uppercase tracking-wider text-muted-foreground",children:[e.jsx("th",{className:"py-2 pr-4 text-left font-medium",children:"agente"}),e.jsx("th",{className:"py-2 pr-4 text-left font-medium",children:"fluxo"}),e.jsx("th",{className:"py-2 pr-4 text-right font-medium",children:"turnos"}),e.jsx("th",{className:"py-2 pr-4 text-right font-medium",children:"conversas"}),e.jsx("th",{className:"py-2 pr-4 text-right font-medium",children:"custo/turno"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"custo"})]})}),e.jsx("tbody",{children:De.visiveis.map(t=>{var x;return e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"py-2 pr-4 font-medium",children:t.agente}),e.jsx("td",{className:"py-2 pr-4 text-muted-foreground",children:t.fluxo}),e.jsx("td",{className:"py-2 pr-4 text-right tabular-nums text-muted-foreground",children:M(t.chamadas)}),e.jsx("td",{className:"py-2 pr-4 text-right tabular-nums text-muted-foreground",children:M(t.conversas)}),e.jsx("td",{className:"py-2 pr-4 text-right tabular-nums text-muted-foreground",children:g((x=t.custo_medio_turno_usd)!=null?x:0)}),e.jsx("td",{className:"py-2 text-right font-semibold tabular-nums",children:g(t.custo_usd)})]},`${t.agente}-${t.fluxo}`)})})]})}),e.jsx(gs,{...De,unidade:"agentes"}),((Qe=a.por_agente)!=null?Qe:[]).length===0?e.jsx("p",{className:"px-1 py-6 text-sm text-muted-foreground",children:"Nenhum turno com agente identificado neste período."}):i>0&&e.jsxs("p",{className:"mt-3 text-[11px] text-muted-foreground",children:[M(ce)," de ",M(ce+i)," turnos têm agente identificado. O restante é anterior à coleta por agente — não há retroação."]})]}),e.jsxs(ee,{value:"pessoas",className:"mt-4",children:[e.jsx(le,{descricao:"As pessoas com maior custo",soma:A.reduce((t,x)=>t+x.custo_usd,0),total:q,restante:"O restante está fora do topo do ranking."}),A.some(t=>t.cadastros>1)&&e.jsxs("p",{className:"mb-3 rounded-[var(--radius-md)] border border-[var(--warning)]/40 bg-[var(--warning-bg)] px-3 py-2 text-[11px] leading-relaxed text-[var(--text-2)]",children:["Linhas com ",e.jsx("strong",{children:"“N cadastros”"})," são a mesma pessoa registrada mais de uma vez. A tabela ",e.jsx("code",{children:"pessoa"})," não tem chave de identidade (CPF ou documento), então cada identificação no chat cria um registro novo em vez de reaproveitar o existente — o custo aqui está somado por nome. Homônimos reais, se houver, também caem na mesma linha."]}
1),e.jsx(ds,{rotuloChave:"pessoa",placeholderBusca:"Buscar pessoa…",itens:A.map(t=>({nome:t.nome,chamadas:t.chamadas,custo_usd:t.custo_usd,sub:t.cadastros>1?`${t.cadastros} cadastros`:void 0,tag:t.tipo==="Não identificada"?void 0:t.tipo}))})]}),e.jsxs(ee,{value:"conversas",className:"mt-4",children:[e.jsx(le,{descricao:`As ${a.por_conversa.length} conversas mais caras`,soma:a.por_conversa.reduce((t,x)=>t+(Number(x.custo_usd)||0),0),total:q,restante:"O restante está distribuído nas demais conversas do período."}),e.jsx(ds,{rotuloChave:"conversa",placeholderBusca:"Buscar conversa…",itens:a.por_conversa.map(t=>({nome:t.titulo,chamadas:t.chamadas,custo_usd:t.custo_usd}))})]}),e.jsxs(ee,{value:"rastreio",className:"mt-4",children:[e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"Cada resposta do agente, passo a passo: a partir da pergunta, como ela é processada, para quem é delegada, qual modelo e qual ferramenta — com latência, tokens e custo por passo."}),e.jsx(rs,{dias:p})]})]})]})})]}),e.jsxs("p",{className:"text-[11px] leading-relaxed text-[var(--text-3)]",children:[((Ke=a.cobertura)==null?void 0:Ke.chamadas)>0&&`${Math.round(a.cobertura.chamadas_com_custo/a.cobertura.chamadas*100)}% das chamadas do período com custo apurado. `,je(a.cambio),je(a.cambio)&&" Valor em real é aproximado."]})]})]})]})}export{It as ConsumoAmbientePage};

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.