PageSourceSearch

https://marvenn.ai/assets/admin-dashboard-BXYL3RmL.js

js marvenn.ai collected 2026-10-05 12:15:35 UTC 73,054 bytes, 1 lines download raw bytes

1import{r as C,v as Z,x as ae,j as e,eN as ss,aH as q,bc as Je,b3 as ds,ai as os,bb as ts,bx as as,G as xs,u as Qe,aT as ms,aR as re,aS as Re,aU as hs,J as De,c1 as qe,aq as ke,H as us,ba as js,b4 as gs,a_ as ps,bd as we,en as ce,bu as fs,eO as Ye,c5 as Ns,bt as is,ek as vs,an as Ze,a3 as bs,ah as ys,bk as ws,b1 as Ge,av as ns,eP as Le}from"./vendor-DGvMVYXi.js";import{a as Ss,q as Ee,h as I,B as y,D as _e,o as ks,p as Oe,r as $e,v as Be,t as ze,I as Y,Q as Ve,C as h,b as j,c as g,e as u,d as z,u as Cs,a2 as T,A as ne,f as le}from"./index-CPX2cHFp.js";import{N as As}from"./navigation-CcENAcSp.js";import{B as A}from"./badge-COnvzEf9.js";import{T as Is,a as Ps,b as G,c as J}from"./tabs-C245byfV.js";import{T as ee,a as se,b as R,c,d as te,e as n}from"./table-CyNZVVWC.js";import{S as Ce,a as Ae,b as Ie,c as Pe,d as Q}from"./select-y3Ncnru8.js";import{T as Ke}from"./textarea-C6xKemI9.js";import{S as He}from"./switch-Duw2ypFc.js";import{L as V}from"./label-Dm3OlCQF.js";import{D as Fs,a as Ts,b as Us,e as Ms,c as Se,d as Ls}from"./dropdown-menu-BDWL7jNN.js";import{S as je}from"./separator-CtMC4X3f.js";import"./scroll-area-Ck4DPvdb.js";import"./credit-upgrade-header-jWYGeZzA.js";import"./linkedin-setup-wizard-c05RgmuZ.js";const Xe=[{value:"getting_started",label:"Getting Started"},{value:"features",label:"Features"},{value:"integration",label:"Integration"},{value:"billing",label:"Billing"},{value:"reputation",label:"Reputation & Warming"},{value:"troubleshooting",label:"Troubleshooting"},{value:"api",label:"API & Development"}];function Es(){const{toast:t}=Ss(),[N,v]=C.useState(!1),[r,S]=C.useState(null),[d,x]=C.useState({title:"",content:"",excerpt:"",category:"features",tags:"",isPublished:!0,isPublic:!0}),{data:o=[],isLoading:k,refetch:$}=Z({queryKey:["/api/support/knowledge-base"]}),D=ae({mutationFn:async i=>{const E=i.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"");return I("/api/support/knowledge-base",{method:"POST",body:{...i,slug:E,tags:i.tags.split(",").map(K=>K.trim()).filter(Boolean)}})},onSuccess:()=>{t({title:"Article created",description:"Knowledge base article has been created."}),Ee.invalidateQueries({queryKey:["/api/support/knowledge-base"]}),_()},onError:()=>{t({title:"Error",description:"Failed to create article.",variant:"destructive"})}}),U=ae({mutationFn:async({id:i,data:E})=>I(`/api/support/knowledge-base/${i}`,{method:"PATCH",body:{...E,tags:E.tags.split(",").map(K=>K.trim()).filter(Boolean)}}),onSuccess:()=>{t({title:"Article updated",description:"Knowledge base article has been updated."}),Ee.invalidateQueries({queryKey:["/api/support/knowledge-base"]}),_()},onError:()=>{t({title:"Error",description:"Failed to update article.",variant:"destructive"})}}),W=ae({mutationFn:async i=>I(`/api/support/knowledge-base/${i}`,{method:"DELETE"}),onSuccess:()=>{t({title:"Article deleted",description:"Knowledge base article has been deleted."}),Ee.invalidateQueries({queryKey:["/api/support/knowledge-base"]})},onError:()=>{t({title:"Error",description:"Failed to delete article.",variant:"destructive"})}}),_=()=>{x({title:"",content:"",excerpt:"",category:"features",tags:"",isPublished:!0,isPublic:!0}),S(null),v(!1)},m=i=>{var E;S(i),x({title:i.title,content:i.content,excerpt:i.excerpt||"",category:i.category,tags:((E=i.tags)==null?void 0:E.join(", "))||"",isPublished:i.isPublished,isPublic:i.isPublic}),v(!0)},L=()=>
1{if(!d.title.trim()||!d.content.trim()){t({title:"Validation error",description:"Title and content are required.",variant:"destructive"});return}r?U.mutate({id:r.id,data:d}):D.mutate(d)},l=i=>{var E;return((E=Xe.find(K=>K.value===i))==null?void 0:E.label)||i};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(ss,{className:"w-6 h-6"}),"Knowledge Base Management"]}),e.jsx("p",{className:"text-gray-500 mt-1",children:"Manage FAQ articles that power the AI Assistant and help center"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(y,{variant:"outline",onClick:()=>$(),children:[e.jsx(q,{className:"w-4 h-4 mr-2"}),"Refresh"]}),e.jsxs(_e,{open:N,onOpenChange:v,children:[e.jsx(ks,{asChild:!0,children:e.jsxs(y,{onClick:()=>{_(),v(!0)},children:[e.jsx(Je,{className:"w-4 h-4 mr-2"}),"Add Article"]})}),e.jsxs(Oe,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs($e,{children:[e.jsx(Be,{children:r?"Edit Article":"Create New Article"}),e.jsx(ze,{children:r?"Update the knowledge base article.":"Add a new article to the knowledge base. This will be used by the AI Assistant and shown in the help center."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(V,{htmlFor:"title",children:"Title (Question)"}),e.jsx(Y,{id:"title",placeholder:"e.g., How do I get started with Marvenn?",value:d.title,onChange:i=>x({...d,title:i.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(V,{htmlFor:"content",children:"Content (Answer)"}),e.jsx(Ke,{id:"content",placeholder:"Provide a detailed answer...",rows:8,value:d.content,onChange:i=>x({...d,content:i.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(V,{htmlFor:"excerpt",children:"Excerpt (Optional)"}),e.jsx(Y,{id:"excerpt",placeholder:"Short summary for previews...",value:d.excerpt,onChange:i=>x({...d,excerpt:i.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(V,{htmlFor:"category",children:"Category"}),e.jsxs(Ce,{value:d.category,onValueChange:i=>x({...d,category:i}),children:[e.jsx(Ae,{children:e.jsx(Ie,{})}),e.jsx(Pe,{children:Xe.map(i=>e.jsx(Q,{value:i.value,children:i.label},i.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(V,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(Y,{id:"tags",placeholder:"setup, onboarding, new user",value:d.tags,onChange:i=>x({...d,tags:i.target.value})})]})]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(He,{id:"published",checked:d.isPublished,onCheckedChange:i=>x({...d,isPublished:i})}),e.jsx(V,{htmlFor:"published",children:"Published"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(He,{id:"public",checked:d.isPublic,onCheckedChange:i=>x({...d,isPublic:i})}),e.jsx(V,{htmlFor:"public",children:"Public (visible to all users)"})]})]})]}),e.jsxs(Ve,{children:[e.jsx(y,{variant:"outline",onClick:_,children:"Cancel"}),e.jsx(y,{onClick:L,disabled:D.isPending||U.isPending,children:D.isPending||U.isPending?"Saving...":r?"Update":"Create"})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsx(g,{className:"text-sm font-medium text-gray-500",children:"Total Articles"})}),e.jsx(u,{children:e.jsx("div",{className:"text-2xl font-bold",children:o.length})})]}),e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsx(g,{className:"text-sm font-medium text-gray-500",children:"Published"})}),e.jsx(u,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:o.filter(i=>i.isPublished).length})})]}),e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsx(g,{className:"text-sm font-medium text-gray-500",children:"Drafts"})}),e.jsx(u,{children:e.jsx("div",{className:"text-2xl font-bold text-yellow-600",children:o.filter(i=>!i.isPublished).length})})]}),e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsx(g,{className:"text-sm font-medium text-gray-500",children:"Total Views"})}),e.jsx(u,{children:e.jsx("div",{className:"text-2xl font-bold",children:o.reduce((i,E)=>i+(E.viewCount||0),0)})})]})]}),e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsxs(g,{className:"flex items-center gap-2",children:[e.jsx(ds,{className:"w-5 h-5"}),"Articles"]}),e.jsx(z,{children:"These articles power the AI Assistant responses and are displayed in the user help center"})]}),e.jsx(u,{children:k?e.jsx("div",{className:"text-center py-8 text-gray-500",children:"Loading articles..."}):o.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(os,{className:"w-12 h-12 mx-auto mb-4 text-gray-400"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Articles Yet"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"Create your first knowledge base article to help users and power the AI Assistant."}),e.jsxs(y,{onClick:()=>v(!0),children:[e.jsx(Je,{className:"w-4 h-4 mr-2"}),"Create First Article"]})]}):e.jsxs(ee,{children:[e.jsx(se,{children:e.jsxs(R,{children:[e.jsx(c,{children:"Title"}),e.jsx(c,{children:"Category"}),e.jsx(c,{children:"Status"}),e.jsx(c,{children:"Views"}),e.jsx(c,{children:"Updated"}),e.jsx(c,{className:"text-right",children:"Actions"})]})}),e.jsx(te,{children:o.map(i=>e.jsxs(R,{children:[e.jsx(n,{className:"font-medium max-w-xs truncate",children:i.title}),e.jsx(n,{children:e.jsx(A,{variant:"outline",children:l(i.category)})}),e.jsx(n,{children:i.isPublished?e.jsx(A,{className:"bg-green-100 text-green-800",children:"Published"}):e.jsx(A,{variant:"secondary",children:"Draft"})}),e.jsx(n,{children:i.viewCount||0}),e.jsx(n,{className:"text-sm text-gray-500",children:new Date(i.updatedAt).toLocaleDateString()}),e.jsx(n,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(y,{variant:"ghost",size:"sm",onClick:()=>m(i),children:e.jsx(ts,{className:"w-4 h-4"})}),e.jsx(y,{variant:"ghost",size:"sm",className:"text-red-600 hover:text-red-700",onClick:()=>{confirm("Are you sure you want to delete this article?")&&W.mutate(i.id)},children:e.jsx(as,{className:"w-4 h-4"})})]})})]},i.id))})]})})]})]})}function Rs(){var _,m,L;const{data:t,isLoading:N,isError:v,error:r,refetch:S}=Z({queryKey:["/api/admin/icp-quality"],queryFn:()=>I("/api/admin/icp-quality"),refetchInterval:6e4,retry:!1});if(N)return e.jsx("div",{className:"flex items-center justify-center h-48",children:e.jsx(q,{className:"h-6 w-6 animate-spin text-muted-foreground"})});if(v){const l=((_=r==null?void 0:r.message)==null?void 0:_.includes("403"))||((m=r==null?void 0:r.message)==null?void 0:m.includes("Forbidden"))||((L=r==null?void 0:r.message)==null?void 0:L.includes("forbidden"));return e.jsx(ne,{children:e.jsx(le,{children:l?"You do not have permission to view ICP quality metrics. Super-admin access is required.":`Failed to load ICP quality data: ${(r==null?void 0:r.message)??"
1Unknown error"}`})})}if(!t)return null;const{summary:d,fallbackOverTime:x,qualityDistribution:o,lowQualityEntries:k,usersWithLowQualityICPs:$,totalLogged:D}=t,U=d.totalRequests>0?(d.claudeRequests/d.totalRequests*100).toFixed(1):"0.0",W=Math.max(...(o??[]).map(l=>l.count),1);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsx(g,{className:"text-sm font-medium text-muted-foreground",children:"Total Analyses"})}),e.jsx(u,{children:e.jsx("p",{className:"text-2xl font-bold",children:D})})]}),e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsx(g,{className:"text-sm font-medium text-muted-foreground",children:"Grok Requests"})}),e.jsx(u,{children:e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:d.grokRequests})})]}),e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsx(g,{className:"text-sm font-medium text-muted-foreground",children:"Claude Fallbacks"})}),e.jsx(u,{children:e.jsx("p",{className:"text-2xl font-bold text-amber-600",children:d.claudeRequests})})]}),e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsx(g,{className:"text-sm font-medium text-muted-foreground",children:"Fallback Rate"})}),e.jsx(u,{children:e.jsxs("p",{className:"text-2xl font-bold text-red-600",children:[U,"%"]})})]})]}),e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsx(g,{children:"Model Usage Breakdown"}),e.jsx(z,{children:"Side-by-side comparison of Grok vs Claude performance and cost"})]}),e.jsxs(u,{children:[e.jsxs(ee,{children:[e.jsx(se,{children:e.jsxs(R,{children:[e.jsx(c,{children:"Model"}),e.jsx(c,{className:"text-right",children:"Requests"}),e.jsx(c,{className:"text-right",children:"Success Rate"}),e.jsx(c,{className:"text-right",children:"Avg Cost"})]})}),e.jsxs(te,{children:[e.jsxs(R,{children:[e.jsx(n,{className:"font-medium",children:e.jsx(A,{variant:"outline",className:"text-blue-600 border-blue-600",children:"Grok (primary)"})}),e.jsx(n,{className:"text-right",children:d.grokRequests}),e.jsx(n,{className:"text-right",children:e.jsxs("span",{className:"font-bold text-green-600",children:[(d.grokSuccessRate*100).toFixed(1),"%"]})}),e.jsxs(n,{className:"text-right",children:["$",d.averageGrokCost.toFixed(4)]})]}),e.jsxs(R,{children:[e.jsx(n,{className:"font-medium",children:e.jsx(A,{variant:"outline",className:"text-amber-600 border-amber-600",children:"Claude (fallback)"})}),e.jsx(n,{className:"text-right",children:d.claudeRequests}),e.jsx(n,{className:"text-right",children:e.jsxs("span",{className:"font-bold text-green-600",children:[(d.claudeSuccessRate*100).toFixed(1),"%"]})}),e.jsxs(n,{className:"text-right",children:["$",d.averageClaudeCost.toFixed(4)]})]})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["Estimated cost savings vs Claude-only: ",e.jsxs("span",{className:"font-bold text-green-600",children:["$",d.totalCostSavings.toFixed(4)]})]})]})]}),e.jsxs(h,{children:[e.jsx(j,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(g,{children:"Quality Score Distribution"}),e.jsx(z,{children:"Histogram of assessQuality() scores across all logged analyses"})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>S(),children:[e.jsx(q,{className:"h-4 w-4 mr-1"})," Refresh"]})]})}),e.jsx(u,{children:(o??[]).length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No quality scores recorded yet."}):e.jsxs("div",{className:"space-y-2",children:[o.map(l=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"w-20 text-xs font-mono text-muted-foreground",children:l.range}),e.jsx("div",{className:"flex-1 bg-muted rounded-full h-4 overflow-hidden",children:e.jsx("div",{className:`h-4 rounded-full transition-all ${parseFloat(l.range)>=.7?"bg-green-500":parseFloat(l.range)>=.4?"bg-amber-400":"bg-red-500"}`,style:{width:`${Math.round(l.count/W*100)}%`}})}),e.jsx("span",{className:"w-10 text-right text-sm font-bold",children:l.count})]},l.range)),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Green ≥ 0.7 · Amber 0.4–0.7 · Red < 0.4"})]})})]}),e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsx(g,{children:"Fallback Rate Over Time"}),e.jsx(z,{children:"Daily breakdown of Claude fallback usage"})]}),e.jsx(u,{children:(x??[]).length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No data yet — runs will appear here after the first analysis."}):e.jsxs(ee,{children:[e.jsx(se,{children:e.jsxs(R,{children:[e.jsx(c,{children:"Date"}),e.jsx(c,{className:"text-right",children:"Total"}),e.jsx(c,{className:"text-right",children:"Fallbacks"}),e.jsx(c,{className:"text-right",children:"Rate"})]})}),e.jsx(te,{children:x.slice(-14).reverse().map(l=>e.jsxs(R,{children:[e.jsx(n,{className:"font-mono text-sm",children:l.date}),e.jsx(n,{className:"text-right",children:l.total}),e.jsx(n,{className:"text-right",children:l.fallbacks}),e.jsx(n,{className:"text-right",children:e.jsxs(A,{variant:l.fallbackRate>.3?"destructive":l.fallbackRate>.1?"secondary":"outline",children:[(l.fallbackRate*100).toFixed(0),"%"]})})]},l.date))})]})})]}),e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsx(g,{children:"Users with Suspected Generic ICPs (Score < 0.7)"}),e.jsx(z,{children:"Users whose analyses produced low-quality ICP output — click an email to search for the user"})]}),e.jsx(u,{children:($??[]).length===0?e.jsxs("p",{className:"text-muted-foreground text-sm",children:["No user-attributed low-quality ICPs in the current log.",(k??[]).length>0&&" Some analyses were logged before user tracking was enabled — see the raw entries table below."]}):e.jsxs(ee,{children:[e.jsx(se,{children:e.jsxs(R,{children:[e.jsx(c,{children:"User"}),e.jsx(c,{className:"text-right",children:"Worst Score"}),e.jsx(c,{className:"text-right",children:"Occurrences"}),e.jsx(c,{className:"text-right",children:"Fallbacks"}),e.jsx(c,{children:"ICP Summary Snippet"}),e.jsx(c,{children:"Last Seen"})]})}),e.jsx(te,{children:$.map(l=>e.jsxs(R,{children:[e.jsx(n,{children:e.jsx("button",{className:"text-blue-600 hover:underline text-sm font-medium text-left",onClick:()=>{const i=document.querySelector('[data-state="inactive"][value="users"]');i&&i.click()},title:"Click to go to Users tab to look up this user",children:l.userEmail||l.userId})}),e.jsx(n,{className:"text-right",children:e.jsx("span",{className:`font-bold ${l.worstScore<.4?"text-red-600":"text-amber-600"}`,children:l.worstScore.toFixed(2)})}),e.jsx(n,{className:"text-right",children:l.entryCount}),e.jsx(n,{className:"text-right",children:l.fallbackCount}),e.jsx(n,{className:"text-xs text-muted-foreground max-w-[240px]",children:e.jsx("span",{className:"line-clamp-2",children:l.worstScoreIcpSummary||"—"})}),e.jsx(n,{className:"text-xs whitespace-nowrap",children:l.latestTimestamp?new Date(l.latestTimestamp).toLocaleStr
1ing():"—"})]},l.userId))})]})})]}),e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsx(g,{children:"Low Quality Analyses (Score < 0.7)"}),e.jsx(z,{children:"Recent analyses with suspected generic or low-quality ICP output"})]}),e.jsx(u,{children:(k??[]).length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No low-quality analyses in the log."}):e.jsxs(ee,{children:[e.jsx(se,{children:e.jsxs(R,{children:[e.jsx(c,{children:"Time"}),e.jsx(c,{children:"User"}),e.jsx(c,{children:"Model"}),e.jsx(c,{className:"text-right",children:"Score"}),e.jsx(c,{children:"Fallback"}),e.jsx(c,{className:"text-right",children:"Cost ($)"}),e.jsx(c,{children:"ICP Snippet"})]})}),e.jsx(te,{children:k.map((l,i)=>{var E;return e.jsxs(R,{children:[e.jsx(n,{className:"text-xs font-mono whitespace-nowrap",children:l.timestamp?new Date(l.timestamp).toLocaleString():"—"}),e.jsx(n,{className:"text-xs",children:l.userEmail??e.jsx("span",{className:"text-muted-foreground",children:"unknown"})}),e.jsx(n,{children:e.jsx(A,{variant:"outline",className:"text-xs",children:(E=l.model)!=null&&E.startsWith("grok-")?"Grok":"Claude"})}),e.jsx(n,{className:"text-right",children:e.jsx("span",{className:`font-bold ${(l.qualityScore??0)<.4?"text-red-600":"text-amber-600"}`,children:(l.qualityScore??0).toFixed(2)})}),e.jsx(n,{children:l.fallbackUsed?e.jsx(A,{variant:"secondary",children:"Yes"}):e.jsx(A,{variant:"outline",children:"No"})}),e.jsx(n,{className:"text-right",children:l.cost.toFixed(4)}),e.jsx(n,{className:"text-xs text-muted-foreground max-w-[240px]",children:e.jsx("span",{className:"line-clamp-2",children:l.icpSummary??l.error??"—"})})]},i)})})]})})]})]})}function Ds(){var o,k;const{data:t,isLoading:N,isError:v,error:r,refetch:S,dataUpdatedAt:d}=Z({queryKey:["/api/admin/intent-health/linkedin-auth-abort/status"],queryFn:()=>I("/api/admin/intent-health/linkedin-auth-abort/status"),refetchInterval:3e4,retry:!1}),x=t&&t.rollingHourCount>=t.threshold;return e.jsx("div",{className:"space-y-6",children:e.jsxs(h,{children:[e.jsx(j,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(g,{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-5 w-5"}),"LinkedIn Auth Abort Monitor"]}),e.jsx(z,{children:"Rolling 1-hour count of LinkedIn session auth abort events from the DM fallback sweep. An alert email fires when the count reaches the configured threshold and a cooldown has elapsed."})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>S(),disabled:N,children:[e.jsx(q,{className:`h-4 w-4 mr-2 ${N?"animate-spin":""}`}),"Refresh"]})]})}),e.jsxs(u,{children:[v&&e.jsx(ne,{children:e.jsx(le,{children:(o=r==null?void 0:r.message)!=null&&o.includes("403")||(k=r==null?void 0:r.message)!=null&&k.includes("Forbidden")?"You do not have permission to view this status. Super-admin access is required.":`Failed to load auth abort status: ${(r==null?void 0:r.message)??"Unknown error"}`})}),N&&!t&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx(q,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),t&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsxs(g,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:[e.jsx(re,{className:"h-3.5 w-3.5"}),"Aborts (last hour)"]})}),e.jsxs(u,{children:[e.jsx("p",{className:`text-2xl font-bold ${x?"text-red-600":"text-green-600"}`,children:t.rollingHourCount}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"rolling 1-hour window"})]})]}),e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsxs(g,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:[e.jsx(De,{className:"h-3.5 w-3.5"}),"Alert Threshold"]})}),e.jsxs(u,{children:[e.jsx("p",{className:"text-2xl font-bold",children:t.threshold}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"events / hour"})]})]}),e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsxs(g,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:[e.jsx(Ge,{className:"h-3.5 w-3.5"}),"Last Alert Sent"]})}),e.jsxs(u,{children:[e.jsx("p",{className:"text-2xl font-bold",children:t.lastAlertSentAt?ce(new Date(t.lastAlertSentAt),"HH:mm"):"—"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.lastAlertSentAt?ce(new Date(t.lastAlertSentAt),"MMM d, yyyy"):"no alert sent yet"})]})]})]}),e.jsx(ne,{className:x?"border-red-300 bg-red-50 dark:bg-red-950/20":"",children:e.jsx(le,{className:"text-sm space-y-1",children:x?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"font-medium text-red-700 dark:text-red-400",children:["⚠️ Threshold breached — ",t.rollingHourCount," abort(s) in the last hour"]}),e.jsxs("p",{className:"text-muted-foreground",children:["One or more LinkedIn accounts likely have expired sessions. Identify accounts with ",e.jsx("code",{className:"text-xs font-mono bg-muted px-1 py-0.5 rounded",children:"requiresActivation = true"})," and ask affected users to reconnect their LinkedIn session."]})]}):e.jsx("p",{className:"text-muted-foreground",children:"Auth abort count is below the alert threshold. LinkedIn session health looks normal. This panel auto-refreshes every 30 seconds."})})}),d>0&&e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:["Last updated: ",new Date(d).toLocaleTimeString()]})]})]})]})})}function qs(){var k,$;const{data:t,isLoading:N,isError:v,error:r,refetch:S,dataUpdatedAt:d}=Z({queryKey:["/api/admin/linkedin-rate-limiter/status"],queryFn:()=>I("/api/admin/linkedin-rate-limiter/status"),refetchInterval:3e4,retry:!1}),x=t?Math.round(t.requestsLastMinute/t.cap*100):0;function o({pct:D}){const U=D>=90?"bg-red-500":D>=60?"bg-yellow-500":"bg-green-500";return e.jsx("div",{className:"w-full bg-muted rounded-full h-3 overflow-hidden",children:e.jsx("div",{className:`h-3 rounded-full transition-all duration-500 ${U}`,style:{width:`${Math.min(D,100)}%`}})})}return e.jsx("div",{className:"space-y-6",children:e.jsxs(h,{children:[e.jsx(j,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(g,{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"h-5 w-5"}),"LinkedIn API Rate Limiter"]}),e.jsxs(z,{children:["Token-bucket status for LinkedIn Voyager URN resolution. Controlled by the"," ",e.jsx("code",{className:"text-xs font-mono bg-muted px-1 py-0.5 rounded",children:"LINKEDIN_URN_RATE_LIMIT_PER_MIN"})," ","environment variable."]})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>S(),disabled:N,children:[e.jsx(q,{className:`h-4 w-4 mr-2 ${N?"animate-spin":""}`}),"Refresh"]})]})}),e.jsxs(u,{children:[v&&e.jsx(ne,{children:e.jsx(le,{children:(k=r==null?void 0:r.message)!=null&&k.includes("403")||($=r==null?void 0:r.message)!=null&&$.includes("Forbidden")?"You do not have permission to view rate limiter status. Super-admin access is required.":`Failed to load rate limiter status: ${(r==null?void 0:r.message)??"
1Unknown error"}`})}),N&&!t&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx(q,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),t&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsxs(g,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:[e.jsx(ns,{className:"h-3.5 w-3.5"}),"Tokens Available"]})}),e.jsxs(u,{children:[e.jsx("p",{className:"text-2xl font-bold text-green-600",children:t.tokensAvailable}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["of ",t.cap," cap"]})]})]}),e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsxs(g,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:[e.jsx(re,{className:"h-3.5 w-3.5"}),"Requests (last 60s)"]})}),e.jsxs(u,{children:[e.jsx("p",{className:`text-2xl font-bold ${x>=90?"text-red-600":x>=60?"text-yellow-600":"text-blue-600"}`,children:t.requestsLastMinute}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["of ",t.cap," limit"]})]})]}),e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsxs(g,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:[e.jsx(qe,{className:"h-3.5 w-3.5"}),"Rate Cap"]})}),e.jsxs(u,{children:[e.jsx("p",{className:"text-2xl font-bold",children:t.cap}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"requests / min"})]})]}),e.jsxs(h,{children:[e.jsx(j,{className:"pb-2",children:e.jsxs(g,{className:"text-sm font-medium text-muted-foreground flex items-center gap-1",children:[e.jsx(Ge,{className:"h-3.5 w-3.5"}),"Next Token In"]})}),e.jsxs(u,{children:[e.jsx("p",{className:"text-2xl font-bold",children:t.msUntilNextToken===0?"—":`${(t.msUntilNextToken/1e3).toFixed(1)}s`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.msUntilNextToken===0?"tokens available now":"until next token"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Usage last 60s"}),e.jsxs("span",{className:"font-medium",children:[x,"%"]})]}),e.jsx(o,{pct:x}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x>=90?"Near limit — consider raising LINKEDIN_URN_RATE_LIMIT_PER_MIN if LinkedIn allows more throughput.":x>=60?"Moderate usage — monitor closely during batch runs.":"Healthy usage — well within the configured limit."})]}),e.jsx(ne,{children:e.jsxs(le,{className:"text-sm space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Tuning guidance"}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground space-y-0.5",children:[e.jsxs("li",{children:['If "Tokens Available" is frequently 0, increase ',e.jsx("code",{className:"font-mono text-xs",children:"LINKEDIN_URN_RATE_LIMIT_PER_MIN"})," (LinkedIn's safe limit is typically 60/min per session)."]}),e.jsx("li",{children:"If LinkedIn starts returning 429 or account warnings, lower the cap."}),e.jsx("li",{children:"This panel auto-refreshes every 5 seconds."})]})]})}),d>0&&e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:["Last updated: ",new Date(d).toLocaleTimeString()]})]})]})]})})}function _s(){const t=Qe(),[N,v]=C.useState(""),[r,S]=C.useState("all"),d=new URLSearchParams;r!=="all"&&d.set("status",r);const{data:x=[],isLoading:o,refetch:k}=Z({queryKey:["/api/admin/monitor-health",r],queryFn:()=>I(`/api/admin/monitor-health?${d}`)}),$=ae({mutationFn:async m=>I(`/api/admin/users/${m}/impersonate`,{method:"POST"}),onSuccess:(m,L)=>{t.invalidateQueries({queryKey:["/api/auth/user"]}),window.location.href="/intent-signals"},onError:m=>{T({title:"Impersonation failed",description:m.message,variant:"destructive"})}}),D=x.filter(m=>N?(m.userEmail||"").toLowerCase().includes(N.toLowerCase()):!0),U={};for(const m of D){const L=m.userEmail||m.userId;U[L]||(U[L]=[]),U[L].push(m)}function W({status:m}){const L={healthy:{label:"Healthy",className:"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"},warning:{label:"Warning",className:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"},not_configured:{label:"Not Configured",className:"bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200"},inactive:{label:"Inactive",className:"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400"}},{label:l,className:i}=L[m]||{label:m,className:"bg-gray-100 text-gray-600"};return e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${i}`,children:l})}const _={};for(const m of x)_[m.status]=(_[m.status]||0)+1;return e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsxs(g,{className:"flex items-center gap-2",children:[e.jsx(re,{className:"h-5 w-5"}),"Monitor Health"]}),e.jsx(z,{children:"All intent signal monitors across all users. Identify broken or misconfigured monitors and jump into client accounts to fix them."})]}),e.jsxs(u,{className:"space-y-4",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(_).map(([m,L])=>e.jsxs("button",{onClick:()=>S(r===m?"all":m),className:"flex items-center gap-1",children:[e.jsx(W,{status:m}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["×",L]})]},m))}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex-1",children:e.jsx(Y,{placeholder:"Filter by user email...",value:N,onChange:m=>v(m.target.value)})}),e.jsxs(Ce,{value:r,onValueChange:S,children:[e.jsx(Ae,{className:"w-44",children:e.jsx(Ie,{placeholder:"All statuses"})}),e.jsxs(Pe,{children:[e.jsx(Q,{value:"all",children:"All Statuses"}),e.jsx(Q,{value:"healthy",children:"Healthy"}),e.jsx(Q,{value:"warning",children:"Warning"}),e.jsx(Q,{value:"not_configured",children:"Not Configured"}),e.jsx(Q,{value:"inactive",children:"Inactive"})]})]}),e.jsx(y,{variant:"outline",size:"icon",onClick:()=>k(),title:"Refresh",children:e.jsx(q,{className:"h-4 w-4"})})]}),o?e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx(q,{className:"h-6 w-6 animate-spin text-gray-400"})}):Object.keys(U).length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No monitors found."}):e.jsx("div",{className:"space-y-6",children:Object.entries(U).map(([m,L])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground",children:m}),e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>$.mutate(L[0].userId),disabled:$.isPending,children:[e.jsx(ws,{className:"h-3.5 w-3.5 mr-1.5"}),"View as User"]}
1)]}),e.jsxs(ee,{children:[e.jsx(se,{children:e.jsxs(R,{children:[e.jsx(c,{children:"Monitor"}),e.jsx(c,{children:"Type"}),e.jsx(c,{children:"Status"}),e.jsx(c,{children:"Last Scanned"}),e.jsx(c,{className:"text-right",children:"Signals"}),e.jsx(c,{className:"text-right",children:"Leads"}),e.jsx(c,{children:"Zero Reason"})]})}),e.jsx(te,{children:L.map(l=>{var i;return e.jsxs(R,{children:[e.jsx(n,{className:"font-medium",children:l.name}),e.jsx(n,{className:"capitalize text-sm",children:(i=l.monitorType)==null?void 0:i.replace(/_/g," ")}),e.jsx(n,{children:e.jsx(W,{status:l.status})}),e.jsx(n,{className:"text-sm text-muted-foreground",children:l.lastScannedAt?ce(new Date(l.lastScannedAt),"MMM d, h:mm a"):"—"}),e.jsx(n,{className:"text-right text-sm",children:l.totalSignalsDetected??0}),e.jsx(n,{className:"text-right text-sm",children:l.totalLeadsFound??0}),e.jsx(n,{className:"text-sm text-muted-foreground max-w-xs truncate",title:l.zeroReason||"",children:l.zeroReason||"—"})]},l.id)})})]})]},m))})]})]})}function Os(){const t=Qe(),{data:N=[],isLoading:v}=Z({queryKey:["/api/admin/system-settings"],queryFn:()=>I("/api/admin/system-settings")}),r=N.find(o=>o.key==="intelligent_cascade_enabled"),S=(r==null?void 0:r.value)==="true",d=ae({mutationFn:async({key:o,value:k})=>I("/api/admin/system-settings",{method:"PUT",body:JSON.stringify({key:o,value:k})}),onSuccess:()=>{t.invalidateQueries({queryKey:["/api/admin/system-settings"]}),T({title:"Settings updated",description:"System settings have been successfully updated."})},onError:o=>{T({title:"Error",description:o.message||"Failed to update settings",variant:"destructive"})}}),x=o=>{d.mutate({key:"intelligent_cascade_enabled",value:String(o)})};return v?e.jsx(h,{children:e.jsx(u,{className:"pt-6",children:e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx(q,{className:"h-6 w-6 animate-spin text-gray-400"})})})}):e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsxs(g,{className:"flex items-center gap-2",children:[e.jsx(ys,{className:"h-5 w-5"}),"System Settings"]}),e.jsx(z,{children:"Configure system-wide features and optimizations"})]}),e.jsx(u,{className:"space-y-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Lead Enrichment"}),e.jsx(je,{}),e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-950 dark:to-emerald-950",children:[e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(V,{htmlFor:"intelligent-cascade",className:"text-base font-semibold cursor-pointer",children:"Intelligent Enrichment Cascade"}),e.jsx(A,{variant:"outline",className:"bg-white dark:bg-gray-800",children:"Cost Optimizer"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"AI learns which data providers work best for different contexts and only uses secondary providers when needed. Reduces enrichment costs by 30-50% system-wide."}),e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Re,{className:"h-3 w-3"}),e.jsx("span",{children:"Machine learning-based provider selection"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(re,{className:"h-3 w-3"}),e.jsx("span",{children:"Field-gap detection to minimize API calls"})]})]})]}),e.jsx(He,{id:"intelligent-cascade",checked:S,onCheckedChange:x,disabled:d.isPending,"data-testid":"switch-admin-intelligent-cascade",className:"ml-4"})]}),S&&e.jsxs(ne,{children:[e.jsx(Re,{className:"h-4 w-4"}),e.jsxs(le,{children:[e.jsx("span",{className:"font-semibold",children:"Intelligent Cascade is Active"}),e.jsx("br",{}),"The system is automatically optimizing enrichment costs across all campaigns by:",e.jsxs("ul",{className:"list-disc list-inside mt-2 space-y-1",children:[e.jsx("li",{children:"Learning which providers (Apollo, Hunter) perform best for each region"}),e.jsx("li",{children:"Only calling secondary providers when primary results have missing fields"}),e.jsx("li",{children:"Recording telemetry to continuously improve recommendations"})]})]})]})]})})]})}const ls=[{key:"initializing",label:"Initializing"},{key:"twilio_subaccount",label:"Twilio subaccount"},{key:"sendgrid_subuser",label:"SendGrid subuser"},{key:"email_domain",label:"Sending domain"},{key:"complete",label:"Complete"}],es=ls.map(t=>t.key);function $s({prog:t}){const N=es.indexOf(t.step);return e.jsx("div",{className:"space-y-0.5 mt-1",children:ls.map(({key:v,label:r})=>{const S=es.indexOf(v),d=!!t.errors[v];let x,o="text-muted-foreground";return d?(x=e.jsx("span",{className:"text-red-500",children:"✗"}),o="text-red-600 dark:text-red-400"):t.terminal==="complete"||S<N?(x=e.jsx("span",{className:"text-green-600",children:"✓"}),o="text-green-700 dark:text-green-400"):S===N&&t.terminal!=="failed"?(x=e.jsx(q,{className:"w-2.5 h-2.5 animate-spin text-blue-500 inline"}
1),o="text-blue-600 dark:text-blue-400"):S===N&&t.terminal==="failed"?(x=e.jsx("span",{className:"text-red-500",children:"✗"}),o="text-red-600 dark:text-red-400"):x=e.jsx("span",{className:"text-muted-foreground",children:"·"}),e.jsxs("div",{className:`flex items-center gap-1 text-[11px] leading-tight ${o}`,children:[e.jsx("span",{className:"w-3 text-center flex-shrink-0",children:x}),e.jsx("span",{children:r}),d&&e.jsxs("span",{className:"truncate max-w-[120px] opacity-75",title:t.errors[v],children:["— ",t.errors[v]]})]},v)})})}function Bs(){const[t,N]=C.useState(new Set),[v,r]=C.useState({}),[S,d]=C.useState({}),[x,o]=C.useState(new Set),[k,$]=C.useState(!1),D=k||x.size>0,[U,W]=C.useState(!1),[_,m]=C.useState(""),[L,l]=C.useState(""),[i,E]=C.useState(""),[K,xe]=C.useState(!1),[de,Fe]=C.useState("all"),[Te,w]=C.useState({}),[We,ge]=C.useState(null),{data:ie,isLoading:Ue,refetch:X}=Z({queryKey:["/api/automated-provisioning/admin/health"],queryFn:()=>I("/api/automated-provisioning/admin/health"),refetchInterval:3e4}),{data:me,isLoading:Me,refetch:he}=Z({queryKey:["/api/automated-provisioning/admin/missing-users"],queryFn:()=>I("/api/automated-provisioning/admin/missing-users")}),ue=async(s,p)=>{const{delayMs:f=0,maxPolls:O=90,isBulk:F=!1}=p??{};f>0&&await new Promise(b=>setTimeout(b,f));for(let b=0;b<O;b++){await new Promise(B=>setTimeout(B,2e3));try{const B=await I(`/api/automated-provisioning/admin/reprovision-progress/${s}`),H=B==null?void 0:B.progress;if(H){const rs=H.stepErrors??{};if(r(ye=>({...ye,[s]:{step:H.currentStep,terminal:H.terminalStatus,errors:rs}})),H.terminalStatus==="complete"||H.terminalStatus==="failed"){const ye=H.terminalStatus==="complete";d(cs=>({...cs,[s]:{success:ye,message:ye?"Re-provisioning complete":`Failed at step: ${H.currentStep}`}}));break}}}catch{}}N(b=>{const B=new Set(b);return B.delete(s),B}),F&&o(b=>{const B=new Set(b);return B.delete(s),B}),X()},pe=async s=>{N(p=>new Set([...p,s])),r(p=>({...p,[s]:{step:"initializing",terminal:null,errors:{}}})),d(p=>{const f={...p};return delete f[s],f});try{await I(`/api/automated-provisioning/admin/reprovision/${s}`,{method:"POST"}),ue(s)}catch(p){d(f=>({...f,[s]:{success:!1,message:(p==null?void 0:p.message)||"Failed to start re-provisioning"}})),N(f=>{const O=new Set(f);return O.delete(s),O})}},fe=async()=>{if(!D){$(!0);try{const s=await I("/api/automated-provisioning/admin/reprovision-all-unprovisioned",{method:"POST"});if(s.users&&s.users.length>0){const p=s.users.map(F=>F.userId);T({title:"Bulk Provisioning Started",description:`Provisioning ${p.length} user(s) in the background. Each row shows live step progress.`}),o(new Set(p)),N(F=>
1new Set([...F,...p])),p.forEach(F=>{r(b=>({...b,[F]:{step:"initializing",terminal:null,errors:{}}})),d(b=>{const B={...b};return delete B[F],B})});const f=65e3,O=5*6e4;p.forEach((F,b)=>{const B=b*f,H=Math.ceil(O/2e3);ue(F,{delayMs:B,maxPolls:H,isBulk:!0})})}else T({title:"Bulk Provisioning",description:s.message}),X()}catch(s){T({title:"Bulk Provisioning Failed",description:s==null?void 0:s.message,variant:"destructive"})}finally{$(!1)}}},Ne=async()=>{W(!0);try{const s=await I("/api/automated-provisioning/admin/backfill-domain-ids",{method:"POST"});T({title:"Domain ID Backfill Complete",description:s.message}),X()}catch(s){T({title:"Backfill Failed",description:s==null?void 0:s.message,variant:"destructive"})}finally{W(!1)}},ve=async()=>{if(_.trim())try{const s=await I("/api/automated-provisioning/admin/create-missing-user",{method:"POST",body:JSON.stringify({email:_.trim(),firstName:L.trim()||void 0,lastName:i.trim()||void 0})});T({title:"User Created",description:`User ${s.userEmail} created — provisioning started.`}),m(""),l(""),E(""),xe(!1),X(),he()}catch(s){T({title:"Create User Failed",description:s==null?void 0:s.message,variant:"destructive"})}},be=async s=>{var f,O,F;const p=Te[s];if(!((f=p==null?void 0:p.email)!=null&&f.trim())){T({title:"Email Required",description:"Enter the user's email address first.",variant:"destructive"});return}ge(s);try{const b=await I("/api/automated-provisioning/admin/create-user-from-orphan",{method:"POST",body:JSON.stringify({userId:s,email:p.email.trim(),firstName:((O=p.firstName)==null?void 0:O.trim())||void 0,lastName:((F=p.lastName)==null?void 0:F.trim())||void 0})});T({title:"Orphan User Created",description:`User record created for ${b.userEmail} — provisioning started.`}),w(B=>{const H={...B};return delete H[s],H}),he(),X()}catch(b){T({title:"Failed",description:b==null?void 0:b.message,variant:"destructive"})}finally{ge(null)}},M=ie==null?void 0:ie.summary,oe=(ie==null?void 0:ie.health)??[],a=oe.filter(s=>de==="unprovisioned"?!s.hasSubuser:de==="warnings"?s.warnings.length>0:!0),P=({row:s})=>s.hasSubuser?s.isMasterPrefix?e.jsx(A,{variant:"destructive",children:"Master Fallback"}):s.hasSendingDomain?s.domainAuthenticated?e.jsx(A,{className:"bg-green-600 text-white",children:"Healthy"}):e.jsx(A,{className:"bg-yellow-500 text-white",children:"Domain Pending"}):e.jsx(A,{className:"bg-amber-500 text-white",children:"No Domain"}):e.jsx(A,{variant:"secondary",children:"Not Provisioned"});return e.jsxs("div",{className:"space-y-6",children:[M&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-3",children:[{label:"Total Users",value:M.total,color:""},{label:"Provisioned",value:M.provisioned,color:"text-green-600"},{label:"Unprovisioned",value:M.unprovisioned,color:M.unprovisioned>0?"text-red-600":""},{label:"Master Fallback",value:M.masterPrefix,color:M.masterPrefix>0?"text-red-600":""},{label:"No Domain",value:M.noSendingDomain,color:M.noSendingDomain>0?"text-amber-600":""},{label:"Domain Auth'd",value:M.domainAuthenticated,color:"text-green-600"},{label:"Missing Domain ID",value:M.missingDomainId,color:M.missingDomainId>0?"text-amber-600":""}].map(({label:s,value:p,color:f})=>e.jsxs(h,{children:[e.jsx(j,{className:"pb-1 pt-3 px-3",children:e.jsx(g,{className:"text-xs font-medium text-muted-foreground",children:s})}),e.jsx(u,{className:"pb-3 px-3",children:e.jsx("p",{className:`text-2xl font-bold ${f}`,children:p})})]},s))}),e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsxs(g,{className:"flex items-center gap-2",children:[e.jsx(ke,{className:"w-5 h-5"}),"Email Provisioning Health"]}),e.jsx(z,{children:"Per-user SendGrid subuser state. Re-provision individual users or run a bulk job for all unprovisioned accounts."})]}),e.jsxs(u,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4",children:[e.jsxs(y,{onClick:fe,disabled:D||((M==null?void 0:M.unprovisioned)??0)===0,className:"gap-2",children:[D?e.jsx(q,{className:"w-4 h-4 animate-spin"}):e.jsx(ns,{className:"w-4 h-4"}),D?"Provisioning…":`Provision All Unprovisioned (${(M==null?void 0:M.unprovisioned)??0})`]}),e.jsxs(y,{variant:"outline",onClick:Ne,disabled:U,className:"gap-2",children:[U?e.jsx(q,{className:"w-4 h-4 animate-spin"}):e.jsx(q,{className:"w-4 h-4"}),U?"Backfilling…":"Backfill Domain IDs"]}),e.jsxs(y,{variant:"outline",onClick:()=>X(),className:"gap-2",children:[e.jsx(q,{className:"w-4 h-4"}),"Refresh"]}),e.jsx("div",{className:"ml-auto flex gap-1",children:["all","unprovisioned","warnings"].map(s=>e.jsx(y,{size:"sm",variant:de===s?"default":"outline",onClick:()=>Fe(s),className:"capitalize",children:s==="all"?`All (${oe.length})`:s==="unprovisioned"?`Unprovisioned (${(M==null?void 0:M.unprovisioned)??0}
1)`:`Warnings (${oe.filter(p=>p.warnings.length>0).length})`},s))})]}),Ue?e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx(q,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(ee,{children:[e.jsx(se,{children:e.jsxs(R,{children:[e.jsx(c,{children:"User"}),e.jsx(c,{children:"Status"}),e.jsx(c,{children:"Subuser Name"}),e.jsx(c,{children:"Sending Domain"}),e.jsx(c,{className:"text-center",children:"Domain Auth"}),e.jsx(c,{className:"text-center",children:"API Key"}),e.jsx(c,{className:"text-center",children:"Domain ID"}),e.jsx(c,{children:"Warnings"}),e.jsx(c,{className:"text-right",children:"Action"})]})}),e.jsxs(te,{children:[a.length===0&&e.jsx(R,{children:e.jsx(n,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No rows match the current filter."})}),a.map(s=>{const p=S[s.userId],f=t.has(s.userId),O=v[s.userId];return e.jsxs(R,{className:s.warnings.length>0?"bg-amber-50 dark:bg-amber-950/20":"",children:[e.jsxs(n,{children:[e.jsx("div",{className:"text-sm font-medium",children:s.userEmail??s.userId}),s.businessName&&e.jsx("div",{className:"text-xs text-muted-foreground",children:s.businessName})]}),e.jsx(n,{children:e.jsx(P,{row:s})}),e.jsx(n,{children:e.jsx("span",{className:"text-xs font-mono",children:s.subuserName??"—"})}),e.jsx(n,{children:e.jsx("span",{className:"text-xs",children:s.sendingDomain??"—"})}),e.jsx(n,{className:"text-center",children:s.hasSubuser?s.domainAuthenticated?e.jsx(A,{className:"bg-green-600 text-white text-xs",children:"Yes"}):e.jsx(A,{variant:"secondary",className:"text-xs",children:"No"}):"—"}),e.jsx(n,{className:"text-center",children:s.hasSubuser?s.apiKeyPresent?e.jsx(A,{className:"bg-green-600 text-white text-xs",children:"Yes"}):e.jsx(A,{variant:"destructive",className:"text-xs",children:"Missing"}):"—"}),e.jsx(n,{className:"text-center",children:s.hasSubuser?s.domainIdPresent?e.jsx(A,{className:"bg-green-600 text-white text-xs",children:"Yes"}):e.jsx(A,{variant:"secondary",className:"text-xs",children:"No"}):"—"}),e.jsx(n,{children:s.warnings.length>0?e.jsx("div",{className:"space-y-1",children:s.warnings.map((F,b)=>e.jsxs("div",{className:"text-xs text-amber-700 dark:text-amber-400 flex items-start gap-1",children:[e.jsx("span",{className:"mt-0.5",children:"⚠"}),e.jsx("span",{children:F})]},b))}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsx(n,{className:"text-right",children:e.jsxs("div",{className:"space-y-1 min-w-[130px]",children:[e.jsxs(y,{size:"sm",variant:"outline",disabled:f,onClick:()=>pe(s.userId),className:"gap-1 text-xs w-full",children:[e.jsx(q,{className:`w-3 h-3 ${f?"animate-spin":""}`}),f?"Running…":"Re-provision"]}),(f||O&&O.terminal)&&O&&e.jsx($s,{prog:O}),p&&!f&&!(O!=null&&O.terminal)&&e.jsxs("div",{className:`text-xs ${p.success?"text-green-600":"text-red-600"}`,children:[p.success?"✓":"✗"," ",p.message]})]})})]},s.userId)})]})]})})]})]}),e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsxs(g,{className:"flex items-center gap-2",children:[e.jsx(Le,{className:"w-5 h-5"}),"Missing Users"]}),e.jsx(z,{children:"Agency/client records that reference a user ID not found in the users table, plus a tool to manually create a user record."})]}),e.jsxs(u,{className:"space-y-4",children:[Me?e.jsx("div",{className:"flex items-center justify-center h-16",children:e.jsx(q,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):me&&me.total>0?e.jsx("div",{className:"rounded-md border",children:e.jsxs(ee,{children:[e.jsx(se,{children:e.jsxs(R,{children:[e.jsx(c,{children:"Source Table"}),e.jsx(c,{children:"User ID (orphaned)"}),e.jsx(c,{children:"Agency ID"}),e.jsx(c,{children:"Display / Company Name"}),e.jsx(c,{className:"text-right",children:"Action"})]})}),e.jsx(te,{children:me.missingUsers.map((s,p)=>{const f=Te[s.userId],O=We===s.userId;return e.jsxs(e.Fragment,{children:[e.jsxs(R,{className:"bg-red-50 dark:bg-red-950/20",children:[e.jsx(n,{children:e.jsx(A,{variant:"outline",children:s.sourceTable})}),e.jsx(n,{className:"font-mono text-xs",children:s.userId}),e.jsx(n,{children:s.agencyId}),e.jsx(n,{children:s.displayName??s.companyName??"—"}),e.jsx(n,{className:"text-right",children:e.jsxs(y,{size:"sm",variant:f!=null&&f.open?"secondary":"outline",className:"text-xs gap-1",onClick:()=>w(F=>{var b;return{...F,[s.userId]:{...F[s.userId]??{},email:"",firstName:"",lastName:"",open:!((b=F[s.userId])!=null&&b.open)}}}),children:[e.jsx(Le,{className:"w-3 h-3"}),f!=null&&f.open?"Cancel":"Create User Record"]})})]},`row-${p}`),(f==null?void 0:f.open)&&e.jsx(R,{className:"bg-red-50/60 dark:bg-red-950/10",children:e.jsx(n,{colSpan:5,className:"py-2",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Email *"}),e.jsx(Y,{placeholder:"[email protected]",value:f.email,onChange:F=>w(b=>({...b,[s.userId]:{...b[s.userId],email:F.target.value}})),className:"mt-1 h-8 text-xs w-48"})]}),e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"First Name"}),e.jsx(Y,{placeholder:"First",value:f.firstName,onChange:F=>w(b=>({...b,[s.userId]:{...b[s.userId],firstName:F.target.value}})),className:"mt-1 h-8 text-xs w-32"})]}),e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Last Name"}),e.jsx(Y,{placeholder:"Last",value:f.lastName,onChange:F=>w(b=>({...b,[s.userId]:{...b[s.userId],lastName:F.target.value}})),className:"mt-1 h-8 text-xs w-32"})]}),e.jsxs(y,{size:"sm",disabled:O||!f.email.trim(),onClick:()=>be(s.userId),className:"gap-1 text-xs h-8",children:[O?e.jsx(q,{className:"w-3 h-3 animate-spin"}):e.jsx(Le,{className:"w-3 h-3"}),O?"Creating…":"Create & Provision"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["User will be created with id ",e.jsx("span",{className:"font-mono",children:s.userId})," (preserves existing FK references)"]})]})})},`form-${p}`)]})})})]})}):e.jsx(ne,{children:e.jsx(le,{className:"text-green-700 dark:text-green-400",children:"No orphaned user references detected — all agency/client records have a matching users table row."})}),e.jsxs("div",{className:"border rounded-md p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm font-medium",children:"Create Missing User Record"}),e.jsx(y,{size:"sm",variant:"outline",onClick:()=>xe(s=>!s),children:K?"Hide":"Show Form"})]}),K&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Creates a new user row (with auto-generated ID) and immediately triggers provisioning."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Email *"}
1),e.jsx(Y,{placeholder:"[email protected]",value:_,onChange:s=>m(s.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"First Name"}),e.jsx(Y,{placeholder:"Tom",value:L,onChange:s=>l(s.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Last Name"}),e.jsx(Y,{placeholder:"Smith",value:i,onChange:s=>E(s.target.value),className:"mt-1"})]})]}),e.jsxs(y,{size:"sm",onClick:ve,disabled:!_.trim(),className:"gap-2",children:[e.jsx(is,{className:"w-4 h-4"}),"Create User & Provision"]})]})]})]})]}),e.jsx(Vs,{})]})}const zs={admin_reprovision_user:"Re-provision User",admin_bulk_provision:"Bulk Provision",admin_create_missing_user:"Create Missing User",admin_create_user_from_orphan:"Create User from Orphan",admin_backfill_domain_ids:"Backfill Domain IDs"};function Vs(){const[t,N]=C.useState(1),{data:v,isLoading:r,refetch:S}=Z({queryKey:["/api/automated-provisioning/admin/audit-log",t],queryFn:()=>I(`/api/automated-provisioning/admin/audit-log?page=${t}&limit=50`)}),d=(v==null?void 0:v.entries)??[],x=v==null?void 0:v.pagination;return e.jsxs(h,{children:[e.jsx(j,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(g,{className:"flex items-center gap-2",children:[e.jsx(Ge,{className:"w-5 h-5"}),"Recent Admin Actions"]}),e.jsx(z,{children:"Last 50 provisioning actions — who triggered them, what changed, and the outcome."})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>S(),className:"gap-2",children:[e.jsx(q,{className:"w-4 h-4"}),"Refresh"]})]})}),e.jsx(u,{children:r?e.jsx("div",{className:"flex items-center justify-center h-24",children:e.jsx(q,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):d.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No admin provisioning actions recorded yet."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(ee,{children:[e.jsx(se,{children:e.jsxs(R,{children:[e.jsx(c,{children:"When"}),e.jsx(c,{children:"Actor"}),e.jsx(c,{children:"Action"}),e.jsx(c,{children:"Target User"}),e.jsx(c,{children:"Outcome"}),e.jsx(c,{children:"Details"})]})}),e.jsx(te,{children:d.map(o=>{var k,$;return e.jsxs(R,{children:[e.jsx(n,{className:"text-xs whitespace-nowrap text-muted-foreground",children:o.createdAt?ce(new Date(o.createdAt),"MMM d, yyyy HH:mm"):"—"}),e.jsx(n,{className:"text-xs font-medium",children:o.actorEmail??o.actorUserId??"—"}),e.jsx(n,{children:e.jsx(A,{variant:"outline",className:"text-xs whitespace-nowrap",children:zs[o.action]??o.action})}),e.jsx(n,{className:"text-xs font-mono",children:(k=o.result)!=null&&k.targetUserEmail?o.result.targetUserEmail:($=o.result)!=null&&$.createdEmail?o.result.createdEmail:o.targetUserId??"—"}),e.jsx(n,{children:o.success?e.jsx(A,{className:"bg-green-600 text-white text-xs",children:"Success"}):e.jsx(A,{variant:"destructive",className:"text-xs",children:"Failed"})}),e.jsx(n,{className:"text-xs text-muted-foreground max-w-[200px] truncate",children:o.result?Object.entries(o.result).filter(([D])=>D!=="triggeredBy").map(([D,U])=>`${D}: ${U}`).join(", "):"—"})]},o.id)})})]})}),x&&x.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between mt-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Page ",x.page," of ",x.totalPages," (",x.total," total)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(y,{size:"sm",variant:"outline",disabled:t<=1,onClick:()=>N(o=>Math.max(1,o-1)),children:"Previous"}),e.jsx(y,{size:"sm",variant:"outline",disabled:t>=x.totalPages,onClick:()=>N(o=>o+1),children:"Next"})]})]})]})})]})}function lt(){var he,ue,pe,fe,Ne,ve,be,M,oe;const{user:t,isLoading:N}=Cs(),[,v]=xs(),r=Qe(),[S,d]=C.useState(""),[x,o]=C.useState("all"),[k,$]=C.useState(null),[D,U]=C.useState(!1),[W,_]=C.useState(!1),[m,L]=C.useState(null),[l,i]=C.useState(""),[E,K]=C.useState(""),[xe,de]=C.useState(!1),{data:Fe=[],isLoading:Te}=Z({queryKey:["/api/admin/users",S,x],queryFn:async()=>{const a=new URLSearchParams;return S&&a.append("search",S),x!=="all"&&a.append("role",x),I(`/api/admin/users?${a}`)},enabled:!N&&!!t&&(t.role==="admin"||t.role==="super_admin")}),{data:w,isLoading:We}=Z({queryKey:["/api/admin/stats"],queryFn:()=>I("/api/admin/stats"),enabled:!N&&!!t&&(t.role==="admin"||t.role==="super_admin")}),ge=ae({mutationFn:async({userId:a,role:P})=>I(`/api/admin/users/${a}/role`,{method:"PUT",body:JSON.stringify({role:P})}),onSuccess:()=>{r.invalidateQueries({queryKey:["/api/admin/users"]}),T({title:"Role updated",description:"User role has been updated successfully."}),U(!1)},onError:a=>{T({title:"Error",description:a.message||"Failed to update user role",variant:"destructive"})}}),ie=ae({mutationFn:async({userId:a,status:P})=>I(`/api/admin/users/${a}/status`,{method:"PUT",body:JSON.stringify({status:P})}),onSuccess:()=>{r.invalidateQueries({queryKey:["/api/admin/users"]}),T({title:"Status updated",description:"User status has been updated successfully."})},onError:a=>{T({title:"Error",description:a.message||"Failed to update user status",variant:"destructive"})}}),Ue=ae({mutationFn:async a=>I(`/api/admin/users/${a}`,{method:"DELETE"}),onSuccess:()=>{r.invalidateQueries({queryKey:["/api/admin/users"]}),T({title:"User deleted",description:"User has been deleted successfully."})},onError:a=>{T({title:"Error",description:a.message||"Failed to delete user",variant:"destructive"})}}),X=ae({mutationFn:async({userId:a,voiceProfile:P})=>I(`/api/admin/users/${a}/brand-voice`,{method:"PATCH",body:JSON.stringify({voiceProfile:P})}),onSuccess:a=>{T({title:"Brand voice updated",description:`Voice profile saved. ${a.agentsUpdated??0} agent(s) updated.`}),_(!1),i(""),K(""),L(null)},onError:a=>{T({title:"Error",description:a.message||"Failed to update brand voice",variant:"destructive"})}}),me=async()=>
1{if(!(!m||!l.trim())){de(!0);try{const a=await I(`/api/admin/users/${m.id}/brand-voice`,{method:"PATCH",body:JSON.stringify({articleExcerpts:l})}),P=a.voiceProfile||"",s=a.agentsUpdated??0;P?(K(P),T({title:"Voice synthesized & saved",description:`Profile saved. ${s} agent(s) updated. Review the result below.`})):T({title:"No result",description:"Try adding more article text.",variant:"destructive"})}catch(a){T({title:"Synthesis failed",description:a.message||"Failed to synthesize voice",variant:"destructive"})}finally{de(!1)}}};if(C.useEffect(()=>{!N&&(!t||t.role!=="admin"&&t.role!=="super_admin")&&v("/")},[N,t,v]),N)return e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})});if(!t||t.role!=="admin"&&t.role!=="super_admin")return null;const Me=Fe.filter(a=>{var P;return!(S&&!a.email.toLowerCase().includes(S.toLowerCase())&&!((P=a.name)!=null&&P.toLowerCase().includes(S.toLowerCase()))||x!=="all"&&a.role!==x)});return e.jsxs("div",{className:"min-h-screen bg-gray-50 dark:bg-gray-900",children:[e.jsx(As,{}),e.jsxs("div",{className:"container mx-auto p-6 space-y-8",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Admin Dashboard"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage users and view system analytics"})]}),e.jsxs(y,{onClick:()=>r.invalidateQueries(),children:[e.jsx(q,{className:"mr-2 h-4 w-4"}),"Refresh Data"]})]}),w&&e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(h,{children:[e.jsxs(j,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(g,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(ms,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(u,{children:[e.jsx("div",{className:"text-2xl font-bold",children:w.totalUsers}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["+",w.newUsersThisWeek??0," this week"]})]})]}),e.jsxs(h,{children:[e.jsxs(j,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(g,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(re,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(u,{children:[e.jsx("div",{className:"text-2xl font-bold",children:w.activeUsers}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[w.totalUsers>0?Math.round(w.activeUsers/w.totalUsers*100):0,"% of total"]})]})]}),e.jsxs(h,{children:[e.jsxs(j,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(g,{className:"text-sm font-medium",children:"New Today"}),e.jsx(Re,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(u,{children:[e.jsx("div",{className:"text-2xl font-bold",children:w.newUsersToday??0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"New registrations today"})]})]}),e.jsxs(h,{children:[e.jsxs(j,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(g,{className:"text-sm font-medium",children:"Feature Usage"}),e.jsx(hs,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(u,{children:[e.jsx("div",{className:"text-2xl font-bold",children:Object.values(w.featureUsage??{}).reduce((a,P)=>a+P,0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total feature interactions"})]})]})]}),e.jsxs(Is,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(Ps,{children:[e.jsx(G,{value:"users",children:"Users"}),e.jsx(G,{value:"analytics",children:"Analytics"}),e.jsx(G,{value:"auth-methods",children:"Auth Methods"}),e.jsxs(G,{value:"knowledge-base",children:[e.jsx(ss,{className:"w-4 h-4 mr-1"}),"Knowledge Base"]}),e.jsx(G,{value:"settings",children:"System Settings"}),e.jsx(G,{value:"monitor-health",children:"Monitor Health"}),(t==null?void 0:t.role)==="super_admin"&&e.jsx(G,{value:"icp-quality",children:"ICP Quality"}),(t==null?void 0:t.role)==="super_admin"&&e.jsxs(G,{value:"linkedin-auth-abort",children:[e.jsx(De,{className:"w-4 h-4 mr-1"}),"Auth Aborts"]}),(t==null?void 0:t.role)==="super_admin"&&e.jsxs(G,{value:"linkedin-rate-limiter",children:[e.jsx(qe,{className:"w-4 h-4 mr-1"}),"LinkedIn API"]}),(t==null?void 0:t.role)==="super_admin"&&e.jsxs(G,{value:"content-quality",children:[e.jsx(re,{className:"w-4 h-4 mr-1"}),"Content Quality"]}),(t==null?void 0:t.role)==="super_admin"&&e.jsxs(G,{value:"email-provisioning",children:[e.jsx(ke,{className:"w-4 h-4 mr-1"}),"Email Provisioning"]}),(t==null?void 0:t.role)==="super_admin"&&e.jsxs(G,{value:"voice-compliance",onClick:()=>window.location.href="/admin/voice-compliance",children:[e.jsx(us,{className:"w-4 h-4 mr-1"}),"Voice Compliance"]})]}),e.jsx(J,{value:"users",className:"space-y-4",children:e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsx(g,{children:"User Management"}),e.jsx(z,{children:"View and manage all registered users"})]}),e.jsxs(u,{children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx("div",{className:"flex-1",children:e.jsxs("div",{className:"relative",children:[e.jsx(js,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Y,{placeholder:"Search by email or name...",value:S,onChange:a=>d(a.target.value),className:"pl-10"})]})}),e.jsxs(Ce,{value:x,onValueChange:o,children:[e.jsx(Ae,{className:"w-[180px]",children:e.jsx(Ie,{placeholder:"Filter by role"})}),e.jsxs(Pe,{children:[e.jsx(Q,{value:"all",children:"All Roles"}),e.jsx(Q,{value:"user",children:"Users"}),e.jsx(Q,{value:"admin",children:"Admins"}),e.jsx(Q,{value:"super_admin",children:"Super Admins"})]})]}),e.jsxs(y,{variant:"outline",children:[e.jsx(gs,{className:"mr-2 h-4 w-4"}),"Export"]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(ee,{children:[e.jsx(se,{children:e.jsxs(R,{children:[e.jsx(c,{children:"User"}),e.jsx(c,{children:"Role"}),e.jsx(c,{children:"Auth Methods"}),e.jsx(c,{children:"Status"}),e.jsx(c,{children:"Joined"}),e.jsx(c,{children:"Last Login"}),e.jsx(c,{className:"text-right",children:"Actions"})]})}),e.jsx(te,{children:Me.map(a=>e.jsxs(R,{children:[e.jsx(n,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:a.email}),a.name&&e.jsx("div",{className:"text-sm text-muted-foreground",children:a.name})]})}),e.jsx(n,{children:e.jsx(A,{variant:a.role==="super_admin"?"destructive":a.role==="admin"?"default":"secondary",children:a.role})}),e.jsx(n,{children:e.jsxs("div",{className:"flex gap-1",children:[a.authMethods.includes("passkey")&&e.jsx(ps,{className:"h-4 w-4"}),a.authMethods.includes("google")&&e.jsx(we,{className:"h-4 w-4"}),a.authMethods.includes("magicLink")&&e.jsx(ke,{className:"h-4 w-4"})]})}),e.jsx(n,{children:e.jsx(A,{variant:a.status==="active"?"default":a.status==="suspended"?"destructive":"secondary",children:a.status})}),e.jsx(n,{children:ce(new Date(a.createdAt),"MMM d, yyyy")}),e.jsx(n,{children:a.lastLogin?ce(new Date(a.lastLogin),"MMM d, yyyy"):"Never"}),e.jsx(n,{className:"text-right",children:e.jsxs(Fs,{children:[e.jsx(Ts,{asChild:!0,children:e.jsx(y,{variant:"ghost",className:"h-8 w-8 p-0",children:e.jsx(fs,{className:"h-4 w-4"})})}),e.jsxs(Us,{align:"end",children:[e.jsx(Ms,{children:"Actions"}),e.jsxs(Se,{onClick:()=>{$(a),U(!0)},children:[e.jsx(ts,{className:"mr-2 h-4 w-4"}),"Edit Role"]}),e.jsxs(Se,{onClick:async()=>{L(a),i(""),K(""),_(!0);try{const P=await I(`/api/admin/users/${a.id}/brand-voice`);P!=null&&P.brandVoice&&K(P.brandVoice)}catch(P){T({title:"Could not load current brand voice",description:P==null?void 0:P.message,variant:"destructive"})}},children:[e.jsx(Ye,{className:"mr-2 h-4 w-4"}
1),"Update Brand Voice"]}),e.jsx(Se,{onClick:()=>{const P=a.status==="active"?"suspended":"active";ie.mutate({userId:a.id,status:P})},children:a.status==="active"?e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"mr-2 h-4 w-4"}),"Suspend User"]}):e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"mr-2 h-4 w-4"}),"Activate User"]})}),e.jsx(Ls,{}),e.jsxs(Se,{className:"text-red-600",onClick:()=>{confirm("Are you sure you want to delete this user?")&&Ue.mutate(a.id)},children:[e.jsx(as,{className:"mr-2 h-4 w-4"}),"Delete User"]})]})]})})]},a.id))})]})})]})]})}),e.jsx(J,{value:"analytics",className:"space-y-4",children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsx(g,{children:"Feature Usage"}),e.jsx(z,{children:"Most used features across the platform"})]}),e.jsx(u,{children:w&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Campaigns"}),e.jsx("span",{className:"font-bold",children:((he=w.featureUsage)==null?void 0:he.campaigns)??0})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Agents"}),e.jsx("span",{className:"font-bold",children:((ue=w.featureUsage)==null?void 0:ue.agents)??0})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Analytics"}),e.jsx("span",{className:"font-bold",children:((pe=w.featureUsage)==null?void 0:pe.analytics)??0})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Social Media"}),e.jsx("span",{className:"font-bold",children:((fe=w.featureUsage)==null?void 0:fe.socialMedia)??0})]})]})})]}),e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsx(g,{children:"User Growth"}),e.jsx(z,{children:"New user registrations over time"})]}),e.jsx(u,{children:w&&e.jsx("div",{className:"space-y-2",children:(w.userGrowth??w.dailySignups??[]).slice(-7).map(a=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:ce(new Date(a.date),"MMM d")}),e.jsx("span",{className:"font-bold",children:a.count})]},a.date))})})]})]})}),e.jsx(J,{value:"auth-methods",className:"space-y-4",children:e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsx(g,{children:"Authentication Methods"}),e.jsx(z,{children:"Distribution of authentication methods used"})]}),e.jsx(u,{children:w&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vs,{className:"h-4 w-4"}),e.jsx("span",{children:"Passkeys"})]}),e.jsx("span",{className:"font-bold",children:((Ne=w.authMethodDistribution)==null?void 0:Ne.passkey)??w.passkeyAdoption??0})]}),e.jsx(je,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{className:"h-4 w-4"}),e.jsx("span",{children:"Google OAuth"})]}),e.jsx("span",{className:"font-bold",children:((ve=w.authMethodDistribution)==null?void 0:ve.google)??0})]}),e.jsx(je,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{className:"h-4 w-4"}),e.jsx("span",{children:"Microsoft OAuth"})]}),e.jsx("span",{className:"font-bold",children:((be=w.authMethodDistribution)==null?void 0:be.microsoft)??0})]}),e.jsx(je,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we,{className:"h-4 w-4"}),e.jsx("span",{children:"Apple OAuth"})]}),e.jsx("span",{className:"font-bold",children:((M=w.authMethodDistribution)==null?void 0:M.apple)??0})]}),e.jsx(je,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{className:"h-4 w-4"}),e.jsx("span",{children:"Magic Links"})]}),e.jsx("span",{className:"font-bold",children:((oe=w.authMethodDistribution)==null?void 0:oe.magicLink)??w.magicLinkUsage??0})]})]})})]})}),e.jsx(J,{value:"knowledge-base",className:"space-y-4",children:e.jsx(Es,{})}),e.jsx(J,{value:"settings",className:"space-y-4",children:e.jsx(Os,{})}),e.jsx(J,{value:"monitor-health",className:"space-y-4",children:e.jsx(_s,{})}),(t==null?void 0:t.role)==="super_admin"&&e.jsx(J,{value:"icp-quality",className:"space-y-4",children:e.jsx(Rs,{})}),(t==null?void 0:t.role)==="super_admin"&&e.jsx(J,{value:"linkedin-auth-abort",className:"space-y-4",children:e.jsx(Ds,{})}),(t==null?void 0:t.role)==="super_admin"&&e.jsx(J,{value:"linkedin-rate-limiter",className:"space-y-4",children:e.jsx(qs,{})}),(t==null?void 0:t.role)==="super_admin"&&e.jsx(J,{value:"content-quality",className:"space-y-4",children:e.jsxs(h,{children:[e.jsxs(j,{children:[e.jsx(g,{children:"Content Quality Review"}),e.jsx(z,{children:"Generate live AI content samples for all four campaign types, view quality gate results, and leave feedback."})]}),e.jsx(u,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(y,{onClick:()=>v("/admin/content-quality"),className:"gap-2",children:[e.jsx(re,{className:"w-4 h-4"}),"Open Content Quality Review"]}),e.jsx(y,{variant:"outline",onClick:()=>v("/admin/content-review-queue"),className:"gap-2",children:"Critic-Loop Review Queue"})]})})]})}),(t==null?void 0:t.role)==="super_admin"&&e.jsx(J,{value:"email-provisioning",className:"space-y-4",children:e.jsx(Bs,{})})]}),e.jsx(_e,{open:W,onOpenChange:a=>{_(a),a||(i(""),K(""),L(null))},children:e.jsxs(Oe,{className:"max-w-2xl",children:[e.jsxs($e,{children:[e.jsxs(Be,{className:"flex items-center gap-2",children:[e.jsx(Ye,{className:"h-5 w-5 text-purple-600"}),"Update Brand Voice"]}),e.jsxs(ze,{children:[m==null?void 0:m.email," — paste article excerpts to re-synthesize, or edit the voice profile directly."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(V,{htmlFor:"bv-excerpts",className:"flex items-center gap-1",children:["LinkedIn Article Excerpts",e.jsx("span",{className:"text-muted-foreground text-xs font-normal ml-1",children:"(optional — paste 1–3 articles to synthesize)"})]}),e.jsx(Ke,{id:"bv-excerpts",placeholder:"Paste the full text of 1–3 LinkedIn articles the client has written…",className:"min-h-[120px] text-sm font-mono",value:l,onCh
1ange:a=>i(a.target.value)}),e.jsx(y,{variant:"outline",size:"sm",onClick:me,disabled:xe||!l.trim(),className:"gap-1.5",children:xe?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"h-3.5 w-3.5 animate-spin"}),"Synthesizing & Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(bs,{className:"h-3.5 w-3.5"}),"Synthesize & Save Voice"]})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(V,{htmlFor:"bv-profile",children:["Brand Voice Profile",e.jsx("span",{className:"text-muted-foreground text-xs font-normal ml-1",children:"(editable — stored in business profile and all agent configs)"})]}),e.jsx(Ke,{id:"bv-profile",placeholder:"3–4 sentences describing the client's authentic tone, style, vocabulary, and recurring themes…",className:"min-h-[100px] text-sm",value:E,onChange:a=>K(a.target.value)})]})]}),e.jsxs(Ve,{children:[e.jsx(y,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsx(y,{onClick:()=>{m&&E.trim()&&X.mutate({userId:m.id,voiceProfile:E.trim()})},disabled:X.isPending||!E.trim(),children:X.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving…"]}):"Save Voice Profile"})]})]})}),e.jsx(_e,{open:D,onOpenChange:U,children:e.jsxs(Oe,{children:[e.jsxs($e,{children:[e.jsx(Be,{children:"Edit User Role"}),e.jsxs(ze,{children:["Change the role for ",k==null?void 0:k.email]})]}),k&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ce,{defaultValue:k.role,children:[e.jsx(Ae,{children:e.jsx(Ie,{})}),e.jsxs(Pe,{children:[e.jsx(Q,{value:"user",children:"User"}),e.jsx(Q,{value:"admin",children:"Admin"}),e.jsx(Q,{value:"super_admin",disabled:k.email!=="[email protected]",children:"Super Admin"})]})]}),e.jsx(ne,{children:e.jsx(le,{children:"Changing user roles will immediately affect their access to features."})})]}),e.jsxs(Ve,{children:[e.jsx(y,{variant:"outline",onClick:()=>U(!1),children:"Cancel"}),e.jsx(y,{onClick:()=>{if(k){const a=document.querySelector("select");ge.mutate({userId:k.id,role:a.value})}},children:"Update Role"})]})]})})]})]})}export{lt 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.