1import{be as ke,by as e,bE as P,bZ as Ls,b_ as ae,b4 as re,c4 as U,aJ as $e,u as Ae,aW as ee,aZ as Fs,D as Ie,aq as he,K as _e,h as T,i as E,cb as je,c5 as be,f as _,a0 as Ne,k as $,l as I,r as Bs,p as qs,s as Z,aU as us,aH as ys,a3 as Os,b0 as Us,aT as Qs,aN as ws,au as hs,ax as ps,ay as gs,av as js,aw as Se,bs as te}from"./index-BOgKjTHI.js";import{B as F}from"./badge-xYseOKTI.js";import{T as W,d as J,e as A,c as x,a as V,b as c}from"./table-B6Wb7fwb.js";import{S as Y}from"./skeleton-C2m6pwdb.js";import{D as ks,a as Cs,d as Ss,e as Rs,b as As,c as Ds}from"./dialog-BmWTUZlb.js";import{AdminNav as Ks}from"./admin-review-queue-CQ5VZD0q.js";import{A as Re}from"./activity-NJt4tlT_.js";import{C as ve}from"./circle-x-OF_xF7qa.js";import{A as Hs}from"./archive-KB1ib7Fu.js";import{C as Ts}from"./cpu-CoCao4P3.js";import{C as qe}from"./chart-no-axes-column-DRGpsNay.js";import{C as Es}from"./clipboard-check-CqC7xPV_.js";import{P as Pe}from"./play-BPm2UT2S.js";import{R as $s}from"./rotate-ccw-Dc6qEhEM.js";import{B as bs}from"./ban-BBa47r9N.js";import{D as Gs}from"./dollar-sign-BtnkFP63.js";import{C as zs}from"./circle-help-C0TL6m1A.js";import"./star-CPINmHzQ.js";import"./chart-column-DwvD-ANz.js";import"./upload-9yrLFtZf.js";/** 2 * @license lucide-react v0.453.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const Is=ke("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/** 7 * @license lucide-react v0.453.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const Oe=ke("FileWarning",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** 12 * @license lucide-react v0.453.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const Ws=ke("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]]);/** 17 * @license lucide-react v0.453.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const we=ke("OctagonAlert",[["path",{d:"M12 16h.01",key:"1drbdi"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M15.312 2a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586l-4.688-4.688A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2z",key:"1fd625"}]]);/** 22 * @license lucide-react v0.453.0 - ISC 23 * 24 * This source code is licensed under the ISC license. 25 * See the LICENSE file in the root directory of this source tree. 26 */const Js=ke("Server",[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]]);/** 27 * @license lucide-react v0.453.0 - ISC 28 * 29 * This source code is licensed under the ISC license. 30 * See the LICENSE file in the root directory of this source tree. 31 */const Me=ke("Webhook",[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]]);var Vs={};class Zs extends P.Component{constructor(l){super(l),this.state={error:null}}static getDerivedStateFromError(l){return{error:l}}render(){return this.state.error?e.jsx("div",{className:"min-h-screen flex items-center justify-center p-8",children:e.jsxs("div",{className:"max-w-xl w-full bg-red-50 border border-red-200 rounded-xl p-6 space-y-3",children:[e.jsx("p",{className:"font-semibold text-red-800 text-sm",children:"Admin Ops â render error"}),e.jsxs("pre",{className:"text-xs text-red-700 whitespace-pre-wrap break-all bg-red-100 rounded p-3",children:[this.state.error.message,` 32 33`,this.state.error.stack]}),e.jsx("button",{onClick:()=>this.setState({error:null}),className:"text-xs underline text-red-600",children:"Try again"})]})}):this.props.children}}function Ps(a){return a==="healthy"?"text-green-600 dark:text-green-400":a==="warning"?"text-amber-600 dar
33k:text-amber-400":a==="recovered"?"text-teal-600 dark:text-teal-400":"text-red-600 dark:text-red-400"}function Ys(a){return a==="healthy"?"bg-green-50 border-green-200 dark:bg-green-950 dark:border-green-800":a==="warning"?"bg-amber-50 border-amber-200 dark:bg-amber-950 dark:border-amber-800":a==="recovered"?"bg-teal-50 border-teal-200 dark:bg-teal-950 dark:border-teal-800":"bg-red-50 border-red-200 dark:bg-red-950 dark:border-red-800"}function fs({status:a,className:l}){const m=`${l??"w-4 h-4"} ${Ps(a)}`;return a==="healthy"?e.jsx(Z,{className:m}):a==="warning"?e.jsx(ee,{className:m}):a==="recovered"?e.jsx($s,{className:m}):e.jsx(ve,{className:m})}function Le({status:a}){const l=a==="healthy"||a==="recovered"?"outline":a==="warning"?"secondary":"destructive";return e.jsx(F,{variant:l,className:`uppercase text-xs font-mono ${Ps(a)}`,children:a})}function Xs(a){return{pending:"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300",monitoring:"bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-300",provisioned:"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300",refunded:"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300",refund_declined:"bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-300",closed:"bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300"}[a]??"bg-gray-100 text-gray-700"}function ue(a){if(!a)return"â";const l=new Date(a),m=Date.now()-l.getTime(),i=Math.floor(m/36e5);if(i<1)return"< 1h ago";if(i<24)return`${i}h ago`;const r=Math.floor(i/24);return r<30?`${r}d ago`:l.toLocaleDateString()}function K({icon:a,label:l,value:m,sub:i,highlight:r}){const o=r==="red"?"bg-red-50 dark:bg-red-950 border-red-200 dark:border-red-800":r==="amber"?"bg-amber-50 dark:bg-amber-950 border-amber-200 dark:border-amber-800":r==="green"?"bg-green-50 dark:bg-green-950 border-green-200 dark:border-green-800":"",f=r==="red"?"bg-red-100 dark:bg-red-900":r==="amber"?"bg-amber-100 dark:bg-amber-900":r==="green"?"bg-green-100 dark:bg-green-900":"bg-muted",d=r==="red"?"text-red-600":r==="amber"?"text-amber-600":r==="green"?"text-green-600":"text-muted-foreground";return e.jsx(T,{className:`border ${o}`,children:e.jsx(E,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`p-2 rounded-lg ${f} shrink-0`,children:e.jsx(a,{className:`w-4 h-4 ${d}`})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-lg font-bold leading-none truncate",children:m}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:l}),i&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:i})]})]})})})}function et(){var v,k;const{toast:a}=je(),l=be(),[m,i]=P.useState(new Set),r=U({queryKey:["/api/admin-x9k2p7/audit/production-daily"],queryFn:te({on401:"returnNull"}),refetchInterval:12e4}),o=ae({mutationFn:()=>re("/api/admin-x9k2p7/audit/production-daily/run","POST",{sendEmail:!1}),onSuccess:()=>{a({title:"Audit complete",description:"Results saved and displayed below."}),l.invalidateQueries({queryKey:["/api/admin-x9k2p7/audit/production-daily"]})},onError:n=>a({title:"Audit failed",description:n.message,variant:"destructive"})}),f=((v=r.data)==null?void 0:v.latest)??null,d=((k=r.data)==null?void 0:k.history)??[];function h(n){i(b=>{const j=new Set(b);return j.has(n)?j.delete(n):j.add(n),j})}return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Runs daily at 06:00 Zurich time in production. One row stored per run."}),e.jsxs(_,{size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,children:[o.isPending?e.jsx(Ne,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Pe,{className:"w-4 h-4 mr-2"}),"Run Now"]})]}),r.isLoading?e.jsx("div",{className:"space-y-3",children:Array.from({length:4}).map((n,b)=>e.jsx(Y,{className:"h-14"},b))}):f?e.jsxs(T,{className:`border ${Ys(f.overallStatus)}`,children:[e.jsx($,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fs,{status:f.overallStatus,className:"w-5 h-5"}),e.jsx(I,{className:"text-base",children:"Latest Audit"}),e.jsx(Le,{status:f.overallStatus})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsx("span",{children:f.environment}),e.jsx("span",{children:ue(f.runAt)}),e.jsx("span",{className:"font-mono",children:f.runAt?new Date(f.runAt).toLocaleTimeString():"â"})]})]})}),e.jsx(E,{className:"pt-0 space-y-2",children:(f.checks??[]).map(n=>{var b,j;return e.jsxs("div",{className:"border rounded-lg bg-white dark:bg-gray-900 overflow-hidden",children:[e.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3 py-2 text-left hover:bg-muted/40 transition-colors",onClick:()=>h(n.name),children:[e.jsx(fs,{status:n.status}),e.jsx("span",{className:"flex-1 text-sm font-mono text-muted-foreground w-36 shrink-0",children:n.name}),e.jsx("span",{className:"flex-1 text-sm truncate",children:n.message}),m.has(n.name)?e.jsx(Bs,{className:"w-4 h-4 shrink-0"}):e.jsx(qs,{className:"w-4 h-4 shrink-0"})]}),m.has(n.name)&&n.meta&&e.jsx("div",{className:"px-3 pb-3 pt-1 bg-muted/30",children:n.name==="provisioning_reconciliation"&&Array.isArray(n.meta.incidents)&&n.meta.incidents.length>0?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-4 text-xs text-muted-foreground mb-1",children:[e.jsxs("span",{children:["Lookback: ",n.meta.lookbackDays,"d"]}),e.jsxs("span",{className:"text-red-600 font-semibold",children:["Open: ",n.meta.openIncidents]}),e.jsxs("span",{className:"text-teal-600 font-semibold",children:["Resolved: ",n.meta.resolvedIncidents]})]}),e.jsx("div",{className:"overflow-x-auto rounded border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/60 border-b",children:[e.jsx("th",{className:"px-2 py-1.5 text-left font-medium text-muted-foreground",children:"Email"}),e.jsx("th",{className:"px-2 py-1.5 text-left font-medium text-muted-foreground",children:"Paid"}),e.jsx("th",{className:"px-2 py-1.5 text-center font-medium text-muted-foreground",children:"DB User"}),e.jsx("th",{className:"px-2 py-1.5 text-center font-medium text-muted-foreground",children:"Vault"}),e.jsx("th",{className:"px-2 py-1.5 text-left font-medium text-muted-foreground",children:"Source"}),e.jsx("th",{className:"px-2 py-1.5 text-left font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"px-2 py-1.5 text-left font-medium text-muted-foreground",children:"Provisioned"})]})}),e.jsx("tbody",{className:"divide-y",children:n.meta.incidents.map((s,u)=>e.jsxs("tr",{className:"hover:bg-muted/20",children:[e.jsx("td",{className:"px-2 py-1.5 font-mono",children:s.customer_email}),e.jsx("td",{className:"px-2 py-1.5 text-muted-foreground whitespace-nowrap",children:s.paid_at?new Date(s.paid_at).toLocaleDateString("en-GB"):"â"}),e.jsx("td",{className:"px-2 py-1.5 text-center",children:s.db_user_found?"â
":"â"}),e.jsx("td",{className:"px-2 py-1.5 text-center",children:s.active_vault_found?"â
":"â"}),e.jsx("td",{className:"px-2 py-1.5 text-muted-foreground",children:s.recovery_source}),e.jsx("td",{className:`px-2 py-1.5 font-semibold ${s.status==="critical"?"text-red-600":s.status==="recovered"?"text-teal-600":"text-green-600"}`,children:s.status.toUpperCase()}),e.jsx("td",{className:"px-2 py-1.5 text-muted-foreground whitespace-nowrap",children:s.provisioned_at?new Date(s.provisioned_at).toLocaleDateString("en-GB"):"â"})]},u))})]})})]}):n.name==="cancel_safety"?e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-muted-foreground",children:[e.jsxs("span",{children:["Scanned: ",e.jsx("strong",{children:n.meta.totalScanned??"â"})]}),e.jsxs("span",{children:["Would cancel: ",e.jsx("strong",{children:n.meta.wouldCancelC
33ount??0})]}),e.jsxs("span",{children:["Skipped: ",e.jsx("strong",{children:n.meta.wouldSkip??"â"})]}),n.meta.cappedAt&&e.jsxs("span",{className:"text-amber-600",children:["Capped at ",n.meta.cappedAt]})]}),Array.isArray(n.meta.candidates)&&n.meta.candidates.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-amber-700 dark:text-amber-400 mb-1",children:"Internal/test subscriptions (safe to cancel manually):"}),e.jsx("div",{className:"overflow-x-auto rounded border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/60 border-b",children:[e.jsx("th",{className:"px-2 py-1.5 text-left font-medium text-muted-foreground",children:"Subscription ID"}),e.jsx("th",{className:"px-2 py-1.5 text-left font-medium text-muted-foreground",children:"Email"}),e.jsx("th",{className:"px-2 py-1.5 text-left font-medium text-muted-foreground",children:"Plan"}),e.jsx("th",{className:"px-2 py-1.5 text-left font-medium text-muted-foreground",children:"Created"}),e.jsx("th",{className:"px-2 py-1.5 text-left font-medium text-muted-foreground",children:"Period end"})]})}),e.jsx("tbody",{className:"divide-y",children:n.meta.candidates.map((s,u)=>e.jsxs("tr",{className:"hover:bg-muted/20",children:[e.jsx("td",{className:"px-2 py-1.5 font-mono text-xs",children:s.subscriptionId}),e.jsx("td",{className:"px-2 py-1.5 text-muted-foreground",children:s.customerEmail??"â"}),e.jsx("td",{className:"px-2 py-1.5 text-muted-foreground",children:s.plan??"â"}),e.jsx("td",{className:"px-2 py-1.5 text-muted-foreground whitespace-nowrap",children:s.created?new Date(s.created).toLocaleDateString("en-GB"):"â"}),e.jsx("td",{className:"px-2 py-1.5 text-muted-foreground whitespace-nowrap",children:s.currentPeriodEnd?new Date(s.currentPeriodEnd).toLocaleDateString("en-GB"):"â"})]},u))})]})})]}),Array.isArray(n.meta.criticalOrphans)&&n.meta.criticalOrphans.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-red-600 mb-1",children:"â Critical orphans â no DB owner, email unconfirmed:"}),n.meta.criticalOrphans.map((s,u)=>e.jsxs("p",{className:"font-mono text-red-600",children:[s.subId,s.email?` â ${s.email}`:" â no email"]},u))]}),!((b=n.meta.candidates)!=null&&b.length)&&!((j=n.meta.criticalOrphans)!=null&&j.length)&&e.jsx("p",{className:"text-green-600 font-semibold",children:"â No candidates or orphans â all subscriptions are accounted for."})]}):n.name==="backup_sanity"?e.jsxs("div",{className:"space-y-1.5 text-xs",children:[n.meta.heartbeat_tracking_active!==void 0&&e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("span",{className:"text-muted-foreground w-36 shrink-0",children:"Heartbeat tracking"}),e.jsx("span",{className:n.meta.heartbeat_tracking_active?"text-green-600 font-semibold":"text-amber-600",children:n.meta.heartbeat_tracking_active?"active (cronHeartbeats)":"fallback (previous audit row)"})]}),n.meta.last_backup_success_at&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-36 shrink-0",children:"Last success"}),e.jsx("span",{className:"font-mono",children:new Date(n.meta.last_backup_success_at).toLocaleString()})]}),n.meta.last_backup_failure_at&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-36 shrink-0 text-red-500",children:"Last failure"}),e.jsx("span",{className:"font-mono text-red-600",children:new Date(n.meta.last_backup_failure_at).toLocaleString()})]}),n.meta.last_backup_failure_reason&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-36 shrink-0",children:"Failure reason"}),e.jsx("span",{className:"text-red-500 truncate max-w-xs",children:n.meta.last_backup_failure_reason})]}),n.meta.sizeMb!==void 0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-36 shrink-0",children:"Size"}),e.jsxs("span",{children:[n.meta.sizeMb," MB"]})]}),n.meta.backupEnv&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:"text-muted-foreground w-36 shrink-0",children:"Backup env"}),e.jsx("span",{className:"font-mono",children:n.meta.backupEnv})]})]}):e.jsx("pre",{className:"text-xs overflow-auto max-h-48 font-mono text-muted-foreground whitespace-pre-wrap",children:JSON.stringify(n.meta,null,2)})})]},n.name)})})]}):e.jsx(T,{children:e.jsx(E,{className:"py-10 text-center text-sm text-muted-foreground",children:'No audit records foun
33d. Click "Run Now" to run the first audit.'})}),d.length>0&&e.jsxs(T,{children:[e.jsx($,{children:e.jsx(I,{className:"text-sm font-medium text-muted-foreground",children:"Last 14 Runs"})}),e.jsx(E,{className:"p-0",children: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 bg-muted/40",children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium text-xs text-muted-foreground",children:"Date / Time"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium text-xs text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium text-xs text-muted-foreground",children:"Critical"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium text-xs text-muted-foreground",children:"Warnings"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium text-xs text-muted-foreground",children:"Active Subs"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium text-xs text-muted-foreground",children:"Orphan"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium text-xs text-muted-foreground",children:"Would Cancel"})]})}),e.jsx("tbody",{className:"divide-y",children:d.map((n,b)=>{var j,s,u,D,g;return e.jsxs("tr",{className:"hover:bg-muted/20",children:[e.jsx("td",{className:"px-4 py-2 font-mono text-xs text-muted-foreground whitespace-nowrap",children:n.runAt?new Date(n.runAt).toLocaleString():"â"}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(Le,{status:n.overallStatus})}),e.jsx("td",{className:"px-4 py-2 text-right font-mono",children:e.jsx("span",{className:n.failuresCount>0?"text-red-600 font-bold":"text-muted-foreground",children:n.failuresCount})}),e.jsx("td",{className:"px-4 py-2 text-right font-mono",children:e.jsx("span",{className:n.warningsCount>0?"text-amber-600":"text-muted-foreground",children:n.warningsCount})}),e.jsx("td",{className:"px-4 py-2 text-right font-mono text-muted-foreground",children:((j=n.summary)==null?void 0:j.activeStripeSubscriptions)??"â"}),e.jsx("td",{className:"px-4 py-2 text-right font-mono",children:e.jsx("span",{className:(((s=n.summary)==null?void 0:s.activeSubscriptionsWithoutDbOwner)??0)>0?"text-red-600":"text-muted-foreground",children:((u=n.summary)==null?void 0:u.activeSubscriptionsWithoutDbOwner)??"â"})}),e.jsx("td",{className:"px-4 py-2 text-right font-mono",children:e.jsx("span",{className:(((D=n.summary)==null?void 0:D.wouldCancel)??0)>0?"text-amber-600":"text-muted-foreground",children:((g=n.summary)==null?void 0:g.wouldCancel)??"â"})})]},b)})})]})})})]})]})}function st(){var M;const{toast:a}=je(),l=be(),[m,i]=P.useState(null),[r,o]=P.useState(""),[f,d]=P.useState(""),[h,v]=P.useState(""),[k,n]=P.useState(null),[b,j]=P.useState(null);ae({mutationFn:()=>re("/api/admin-x9k2p7/backup/drill","POST").then(p=>p.json()),onSuccess:p=>j(p)});const s=U({queryKey:["/api/admin-x9k2p7/stripe/provisioning-incidents"],queryFn:te({on401:"returnNull"})}),u=ae({mutationFn:({id:p,status:G,resolutionNotes:O,resolutionType:z})=>re(`/api/admin-x9k2p7/stripe/provisioning-incidents/${p}`,"PATCH",{status:G,resolutionNotes:O,...z?{resolutionType:z}:{}}),onSuccess:()=>{a({title:"Incident updated"}),i(null),l.invalidateQueries({queryKey:["/api/admin-x9k2p7/stripe/provisioning-incidents"]}),l.invalidateQueries({queryKey:["/api/admin-x9k2p7/audit/production-daily"]})},onError:p=>a({title:"Update failed",description:p.message,variant:"destructive"})}),D=ae({mutationFn:()=>re("/api/admin-x9k2p7/stripe/run-gap-check?period_days=14","POST"),onSuccess:async p=>{const G=await p.json();n(G),a({title:"Gap check complete"}),l.invalidateQueries({queryKey:["/api/admin-x9k2p7/stripe/provisioning-incidents"]})},onError:p=>a({title:"Gap check failed",description:p.message,variant:"destructive"})}),g=((M=s.data)==null?void 0:M.incidents)??[],S=g.filter(p=>p.status==="pending"||p.status==="monitoring"),N=g.filter(p=>p.status!=="pending"&&p.status!=="monitoring");function H(p){i(p.id),o(p.status),d(p.resolutionNotes??""),v(p.resolutionType??"")}const R={refunded:"Refunded",compensated:"Compensated",provisioned_manually:"Provisioned manually",no_action:"No action taken"};function w({incident:p}){const G=m===p.id,O=p.status==="pending"||p.status==="monitoring",Q=(p.incidentDate?Date.now()-new Date(p.incidentDate).getTime():0)/36e5,le=O&&Q>=48,B=Q>=72?"bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300":"bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300",ie=Q<24?`${Math.floor(Q)}h`:`${Math.floor(Q/24)}d ${Math.floor(Q%24)}h`;return e.jsxs("div",{className:`border rounded-lg p-4 space-y-2 bg-white dark:bg-gray-900 ${Q>=72&&O?"border-red-300 dark:border-red-700":Q>=48&&O?"border-amber-300 dark:border-amber-700":""}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-sm",children:p.email}),e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${Xs(p.status)}`,children:p.status.replace(/_/g," ")}),p.resolutionType&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300 font-medium",children:R[p.resolutionType]??p.resolutionType}),le&&e.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full font-bold ${B}`,children:[Q>=72?"â ":"â± ",ie," old"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[p.amountPaid&&e.jsxs("span",{className:"font-mono",children:[(p.amountPaid/100).toFixed(2)," ",(p.currency??"usd").toUpperCase()]}),p.plan&&e.jsx("span",{className:"bg-muted px-2 py-0.5 rounded",children:p.plan}),e.jsx(Ae,{className:"w-3 h-3"}),e.jsx("span",{children:ue(p.incidentDate)})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground font-mono",children:[p.stripeCustomerId&&e.jsxs("span",{children:["cus: ",p.stripeCustomerId]}),p.stripeSubscriptionId&&e.jsxs("span",{children:["sub: ",p.stripeSubscriptionId]}),p.stripeSessionId&&e.jsxs("span",{children:["cs: ",p.stripeSessionId.slice(0,24),"â¦"]})]}),p.resolutionNotes&&!G&&e.jsx("p",{className:"text-xs text-muted-foreground border-l-2 border-muted pl-2 italic",children:p.resolutionNotes}),G?e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Status"}),e.jsxs(hs,{value:r,onValueChange:o,children:[e.jsx(ps,{className:"h-8 text-sm",children:e.jsx(gs,{})}),e.jsx(js,{children:["pending","monitoring","provisioned","refunded","refund_declined","closed"].map(q=>e.jsx(Se,{value:q,children:q.replace(/_/g," ")},q))})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Resolution type"}),e.jsxs(hs,{value:h,onValueChange:v,children:[e.jsx(ps,{className:"h-8 text-sm",children:e.jsx(gs,{placeholder:"Optionalâ¦"})}),e.jsxs(js,{children:[e.jsx(Se,{value:"refunded",children:"Refunded"}),e.jsx(Se,{value:"compensated",children:"Compensated"}),e.jsx(Se,{value:"provisioned_manually",children:"Provisioned manually"}),e.jsx(Se,{value:"no_action",children:"No action taken"})]})]})]})]}),e.jsx(ws,{placeholder:"Resolution notesâ¦",value:f,onChange:q=>
33d(q.target.value),className:"text-sm min-h-[60px]"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(_,{size:"sm",onClick:()=>u.mutate({id:p.id,status:r,resolutionNotes:f,resolutionType:h}),disabled:u.isPending,children:[u.isPending&&e.jsx(Ne,{className:"w-3 h-3 mr-1 animate-spin"}),"Save"]}),e.jsx(_,{size:"sm",variant:"ghost",onClick:()=>i(null),children:"Cancel"})]})]}):e.jsx(_,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>H(p),children:"Update"})]})}return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Customers who paid but were never provisioned. Auto-scanned daily at 07:00 Zurich (last 14 days)."}),e.jsxs(_,{size:"sm",variant:"outline",onClick:()=>D.mutate(),disabled:D.isPending,children:[D.isPending?e.jsx(Ne,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(he,{className:"w-4 h-4 mr-2"}),"Run Gap Check (14d)"]})]}),k&&e.jsxs(T,{className:"border border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-950",children:[e.jsx($,{className:"pb-2",children:e.jsx(I,{className:"text-sm text-blue-700 dark:text-blue-300",children:"Gap Check Result"})}),e.jsx(E,{children:e.jsx("pre",{className:"text-xs font-mono text-blue-800 dark:text-blue-200 whitespace-pre-wrap overflow-auto max-h-48",children:JSON.stringify(k,null,2)})})]}),s.isLoading?e.jsx("div",{className:"space-y-3",children:Array.from({length:3}).map((p,G)=>e.jsx(Y,{className:"h-24"},G))}):e.jsxs(e.Fragment,{children:[S.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-semibold text-red-700 dark:text-red-400 flex items-center gap-2",children:[e.jsx(we,{className:"w-4 h-4"}),"Needs Action (",S.length,")"]}),S.map(p=>e.jsx(w,{incident:p},p.id))]}),N.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground flex items-center gap-2",children:[e.jsx(Z,{className:"w-4 h-4"}),"Resolved (",N.length,")"]}),N.map(p=>e.jsx(w,{incident:p},p.id))]}),g.length===0&&e.jsx(T,{children:e.jsxs(E,{className:"py-10 text-center text-sm text-muted-foreground",children:[e.jsx(Z,{className:"w-8 h-8 mx-auto mb-2 text-green-500"}),"No provisioning incidents on record."]})})]})]})}function tt({webhookStatus:a}){const{toast:l}=je(),m=be(),[i,r]=P.useState(""),[o,f]=P.useState(!0),[d,h]=P.useState(null),[v,k]=P.useState(null),n=ae({mutationFn:()=>re("/api/admin-x9k2p7/stripe/run-reconcile","POST"),onSuccess:async j=>{const s=await j.json();k(s),m.invalidateQueries({queryKey:["/api/admin-x9k2p7/stripe/provisioning-incidents"]}),l({title:"Reconciliation complete",description:`${s.provisioned??0} provisioned, ${s.updated??0} updated.`})},onError:()=>l({title:"Reconciliation failed",description:"Check server logs.",variant:"destructive"})}),b=ae({mutationFn:j=>re("/api/admin-x9k2p7/stripe/provision-by-session","POST",j),onSuccess:async j=>{const s=await j.json();h(s),m.invalidateQueries({queryKey:["/api/admin-x9k2p7/stripe/provisioning-incidents"]}),l({title:s.action==="provisioned_new"?"New user provisioned":"Existing user updated",description:`${s.email} â email action: ${s.emailAction??"none"}`})},onError:async j=>{l({title:"Provision failed",description:(j==null?void 0:j.message)??"Check server logs.",variant:"destructive"})}});return e.jsxs("div",{className:"space-y-6",children:[(a==="critical"||a==="warning")&&e.jsxs("div",{className:`border rounded-lg p-4 flex items-start gap-3 ${a==="critical"?"border-red-300 bg-red-50 dark:bg-red-950":"border-amber-300 bg-amber-50 dark:bg-amber-950"}`,children:[e.jsx(ee,{className:`w-5 h-5 shrink-0 mt-0.5 ${a==="critical"?"text-red-600":"text-amber-600"}`}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:`font-semibold mb-1 ${a==="critical"?"text-red-800 dark:text-red-200":"text-amber-800 dark:text-amber-200"}`,children:a==="critical"?"Stripe webhook â action required":"Stripe webhook â investigation needed"}),e.jsxs("p",{className:a==="critical"?"text-red-700 dark:text-red-300":"text-amber-700 dark:text-amber-300",children:["The daily audit has flagged a webhook issue. Check the audit tab for the specific failure, then use the tools below to recover missed customers. Webhook endpoint: ",e.jsx("code",{className:`px-1 rounded text-xs ${a==="critical"?"bg-red-100 dark:bg-red-900":"bg-amber-100 dar
33k:bg-amber-900"}`,children:"https://privawell.net/api/stripe/webhook"})]})]})]}),e.jsxs(T,{children:[e.jsx($,{children:e.jsxs(I,{className:"flex items-center gap-2 text-base",children:[e.jsx(he,{className:"w-4 h-4"})," Run Stripe Reconciliation Now"]})}),e.jsxs(E,{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Scans all active Stripe subscriptions and recent paid checkout sessions against the DB. Provisions any missed users and resolves incidents automatically."}),e.jsx(_,{onClick:()=>n.mutate(),disabled:n.isPending,className:"bg-amber-600 hover:bg-amber-700 text-white",children:n.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ne,{className:"w-4 h-4 animate-spin mr-2"}),"Runningâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pe,{className:"w-4 h-4 mr-2"}),"Run reconciliation"]})}),v&&e.jsx("pre",{className:"text-xs bg-gray-100 dark:bg-gray-800 rounded p-3 overflow-auto max-h-48 whitespace-pre-wrap",children:JSON.stringify(v,null,2)})]})]}),e.jsxs(T,{children:[e.jsx($,{children:e.jsxs(I,{className:"flex items-center gap-2 text-base",children:[e.jsx(Me,{className:"w-4 h-4"})," Provision Customer by Stripe Session ID"]})}),e.jsxs(E,{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Paste a ",e.jsx("code",{className:"bg-gray-100 dark:bg-gray-800 px-1 rounded",children:"cs_live_â¦"})," checkout session ID from the Stripe dashboard. The server fetches the customer email and Stripe IDs directly from Stripe and creates (or updates) the DB user."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Stripe checkout session ID"}),e.jsx("input",{type:"text",value:i,onChange:j=>r(j.target.value.trim()),placeholder:"cs_live_...",className:"w-full border rounded-md px-3 py-2 text-sm font-mono bg-white dark:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-amber-500"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"send-email-checkbox",type:"checkbox",checked:o,onChange:j=>f(j.target.checked),className:"rounded border-gray-300"}),e.jsx("label",{htmlFor:"send-email-checkbox",className:"text-sm",children:"Send vault access email to customer after provisioning"})]}),e.jsx(_,{onClick:()=>{if(!i.startsWith("cs_")){l({title:"Invalid session ID",description:"Must start with cs_",variant:"destructive"});return}h(null),b.mutate({session_id:i,sendEmail:o})},disabled:b.isPending||!i,className:"bg-green-700 hover:bg-green-800 text-white",children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ne,{className:"w-4 h-4 animate-spin mr-2"}),"Provisioningâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(Z,{className:"w-4 h-4 mr-2"}),"Provision customer"]})}),d&&e.jsxs("div",{className:`rounded-lg p-3 text-sm border ${d.action==="provisioned_new"?"border-green-300 bg-green-50 dark:bg-green-950 text-green-800 dark:text-green-200":"border-blue-300 bg-blue-50 dark:bg-blue-950 text-blue-800 dark:text-blue-200"}`,children:[e.jsx("p",{className:"font-semibold mb-1",children:d.action==="provisioned_new"?"â
New user provisioned":"ð Existing user updated"}),e.jsxs("p",{children:["Email: ",e.jsx("strong",{children:d.email})]}),e.jsxs("p",{children:["User ID: ",d.userId]}),d.emailAction&&e.jsxs("p",{children:["Email action: ",d.emailAction]}),e.jsxs("p",{children:["Session: ",e.jsx("code",{className:"text-xs",children:d.session_id})]})]})]})]})]})}function at(a,l){if(a!==null)return a>=l?"green":a>=l-10?"amber":"red"}function Ns(a){const l={text_pdf:"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",scanned_pdf:"bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200",mixed_pdf:"bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200",image:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900 dark:text-emerald-200",unknown:"bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300"};return l[a??"unknown"]??l.unknown}function rt(a){return a==="ready"?"text-green-600 dark:text-green-400":a==="partial"?"text-amber-600 dark:text-amber-400":a==="failed"?"text-red-600 dark:text-red-400":a==="processing"?"text-blue-600 dar
33k:text-blue-400":"text-muted-foreground"}function nt(){var b,j;const{toast:a}=je(),l=be(),[m,i]=P.useState(null),r=U({queryKey:["/api/admin-x9k2p7/lab-metrics"],queryFn:te({on401:"returnNull"}),refetchInterval:6e4}),o=U({queryKey:["/api/admin-x9k2p7/lab-extractions"],queryFn:te({on401:"returnNull"}),refetchInterval:3e4}),f=ae({mutationFn:s=>re(`/api/admin-x9k2p7/lab-extractions/${s}/replay`,"POST",{}),onSuccess:()=>{a({title:"Replay started",description:"Pipeline is re-running. Refresh in a moment."}),l.invalidateQueries({queryKey:["/api/admin-x9k2p7/lab-extractions"]})},onError:s=>a({title:"Replay failed",description:s.message,variant:"destructive"})}),d=r.data,h=((b=o.data)==null?void 0:b.extractions)??[],v=d==null?void 0:d.targets,k=(d==null?void 0:d.failureReasons24h)??[],n=k.reduce((s,u)=>s+u.count,0);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3",children:[e.jsx(K,{icon:_e,label:"Overall success",value:d?`${d.totals.successRate??"â"}%`:"â",sub:d?`${d.totals.success}/${d.totals.total} extractions`:"Loadingâ¦",highlight:at((d==null?void 0:d.totals.successRate)??null,(v==null?void 0:v.overall)??90)}),e.jsx(K,{icon:Re,label:"OCR fallback rate",value:d?`${d.fallbackRate??"â"}%`:"â",sub:"Scanned/mixed trigger OCR",highlight:(d==null?void 0:d.fallbackRate)==null?void 0:d.fallbackRate>40?"amber":"green"}),e.jsx(K,{icon:us,label:"Avg duration",value:d!=null&&d.duration.avgMs?`${(d.duration.avgMs/1e3).toFixed(1)}s`:"â",sub:d!=null&&d.duration.p95Ms?`p95: ${(d.duration.p95Ms/1e3).toFixed(1)}s`:"No data"}),e.jsx(K,{icon:Oe,label:"Date ambiguity",value:d?`${d.dateAmbiguityRate??"â"}%`:"â",sub:`Target: <${(v==null?void 0:v.dateErrorMax)??2}%`,highlight:(d==null?void 0:d.dateAmbiguityRate)==null?void 0:d.dateAmbiguityRate<=((v==null?void 0:v.dateErrorMax)??2)?"green":d.dateAmbiguityRate<=((v==null?void 0:v.dateErrorMax)??2)*2?"amber":"red"}),e.jsx(K,{icon:ee,label:"Failures (24h)",value:n,sub:n>0?((j=k[0])==null?void 0:j.reason_code)??"mixed":"Clean",highlight:n>5?"red":n>0?"amber":"green"}),e.jsx(K,{icon:Ie,label:"Total extractions",value:(d==null?void 0:d.totals.total)??"â",sub:d?`${d.totals.failed} failed`:"Loadingâ¦"})]}),d&&d.byMode.length>0&&e.jsxs(T,{children:[e.jsx($,{className:"pb-2",children:e.jsxs(I,{className:"text-base flex items-center gap-2",children:[e.jsx(_e,{className:"w-4 h-4"})," Success rate by document mode"]})}),e.jsx(E,{children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:d.byMode.map(s=>{const u=v==null?void 0:v[s.mode];return e.jsxs("div",{className:"border rounded-lg p-3 text-sm",children:[e.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-xs font-mono mb-2 ${Ns(s.mode)}`,children:s.mode}),e.jsx("p",{className:`text-2xl font-bold ${s.successRate===null?"text-muted-foreground":u&&s.successRate>=u?"text-green-600 dark:text-green-400":u&&s.successRate>=u-10?"text-amber-600":"text-red-600"}`,children:s.successRate!==null?`${s.successRate}%`:"â"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.success,"/",s.total," ok",u!==void 0&&typeof u=="number"&&e.jsxs("span",{className:"ml-1 text-gray-400",children:["· target ",u,"%"]})]})]},s.mode)})})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(T,{children:[e.jsx($,{className:"pb-2",children:e.jsxs(I,{className:"text-base flex items-center gap-2",children:[e.jsx(ee,{className:"w-4 h-4 text-amber-500"})," Top failures (last 24h)"]})}),e.jsx(E,{children:r.isLoading?e.jsx(Y,{className:"h-20"}):k.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No failures in last 24h â"}):e.jsx("div",{className:"space-y-2",children:k.map(s=>e.jsxs("div",{className:"flex items-center justify-between border rounded px-3 py-2 text-sm",children:[e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:s.reason_code}),e.jsx(F,{variant:"destructive",children:s.count})]},s.reason_code))})})]}),e.jsxs(T,{children:[e.jsx($,{className:"pb-2",children:e.jsxs(I,{className:"text-base flex items-center gap-2",children:[e.jsx(ee,{className:"w-4 h-4 text-orange-500"})," Top failures (last 7 days)"]})}),e.jsx(E,{children:r.isLoading?e.jsx(Y,{className:"h-20"}):((d==null?void 0:d.failureReasons7d)??[]).length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No failures in last 7 days â"}):e.jsx("div",{className:"space-y-2",children:((d==null?void 0:d.failureReasons7d)??[]).map(s=>e.jsxs("div",{className:"flex items-center justify-between border rounded px-3 py-2 text-sm",children:[e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:s.reason_code}),e.jsx(F,{variant:"secondary",children:s.count})]},s.reason_code))})})]})]}),d&&d.daily.length>0&&e.jsxs(T,{children:[e.jsx($,{className:"pb-2",children:e.jsxs(I,{className:"text-base flex items-center gap-2",children:[e.jsx(us,{className:"w-4 h-4"})," Daily success rate (last 14 days)"]})}),e.jsx(E,{children:e.jsx("div",{className:"flex items-end gap-1 h-16 overflow-x-auto pb-1",children:d.daily.map(s=>{const u=s.successRate??0,D=Math.max(4,Math.round(u*.6)),g=u>=((v==null?void 0:v.overall)??90)?"bg-green-400 dark:bg-green-500":u>=((v==null?void 0:v.overall)??90)-10?"bg-amber-400":"bg-red-400";return e.jsxs("div",{className:"flex flex-col items-center gap-0.5 shrink-0",title:`${s.day}: ${u}% (${s.success}/${s.total})`,children:[e.jsxs("span",{className:"text-[9px] text-muted-foreground",children:[u,"%"]}),e.jsx("div",{className:`w-6 rounded-sm ${g}`,style:{height:`${D}px`}}),e.jsx("span",{className:"text-[8px] text-muted-foreground rotate-45 origin-left",children:s.day.slice(5)})]},s.day)})})})]}),e.jsxs(T,{children:[e.jsx($,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(I,{className:"text-base flex items-center gap-2",children:[e.jsx(Ie,{className:"w-4 h-4"})," Last 50 extractions"]}),e.jsxs(_,{size:"sm",variant:"outline",onClick:()=>l.invalidateQueries({queryKey:["/api/admin-x9k2p7/lab-extractions"]}),children:[e.jsx(he,{className:"w-3 h-3 mr-1"})," Refresh"]})]})}),e.jsx(E,{className:"p-0",children:o.isLoading?e.jsx("div",{className:"p-4 space-y-2",children:Array.from({length:5}).map((s,u)=>e.jsx(Y,{className:"h-10"},u))}):h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground p-4 text-center",children:"No extractions yet"}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/40",children:[e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Mode"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Path"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Date reason"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Duration"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"When"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Replay"})]})}),e.jsx("tbody",{children:h.map(s=>e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:`border-b hover:bg-muted/30 cursor-pointer ${m===s.id?"bg-muted/20":""}`,onClick:()=>i(u=>u===s.id?null:s.id),children:[e.jsxs("td",{className:`px-3 py-2 font-mono font-semibold ${rt(s.extractionStatus)}`,children:[s.extractionStatus,s.failureReasonCode&&e.jsx("div",{className:"text-[10px] text-red-500 font-normal",children:s.failureReasonCode})]}),e.jsx("td",{className:"px-3 py-2",children:e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono ${Ns(s.documentMode)}`,children:s.documentMode??"?"})}),e.jsx("td",{className:"px-3 py-2 font-mono text-muted-foreground",children:s.extractionPath??"â"}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:s.selectedDateReason??"â"}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:s.durationMs!==null?`${(s.durationMs/1e3).toFixed(1)}s`:"â"}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:ue(s.createdAt)}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs(_,{size:"sm",variant:"outline",className:"h-6 px-2 text-xs",disabled:f.isPending,onClick:u=>{u.stopPropagation(),f.mutate(s.id)},children:[e.jsx($s,{className:"w-3 h-3 mr-1"})," Replay"]})})]},s.id),m===s.id&&e.jsx("tr",{className:"bg-muted/10 border-b",children:e.jsx("td",{colSpan:7,className:"px-4 py-3",children:e.jsxs("div",{className:"text-xs space-y-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-muted-foreground",children:"Lab ID:"})," ",e.jsx("code",{className:"font-mono",children:s.id})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-muted-foreground",children:"Doc ID:"})," ",e.jsx("code",{className:"font-mono",children:s.sourceFileId})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-muted-foreground",children:"User ID:"})," ",e.jsx("code",{className:"font-mono",children:s.userId})]}),s.documentDate&&e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-muted-foreground",children:"Report date:"})," ",s.documentDate]}),s.confidence&&e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-muted-foreground",children:"Confidence:"})," ",s.confidence]}),s.retryCount!==null&&e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-muted-foreground",children:"Retries:"})," ",s.retryCount]}),s.extractionError&&e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-red-500",children:"Error:"})," ",e.jsx("span",{className:"text-red-600",children:s.extractionError})]})]})})},`${s.id}-detail`)]}))})]})})})]}),v&&e.jsxs(T,{children:[e.jsx($,{className:"pb-2",children:e.jsxs(I,{className:"text-base flex items-center gap-2",children:[e.jsx(Z,{className:"w-4 h-4 text-green-500"})," Production success baseline targets"]})}),e.jsx(E,{children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between border rounded px-3 py-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Overall"}),e.jsxs("span",{className:"font-medium",children:["⥠",v.overall,"%"]})]}),e.jsxs("div",{className:"flex justify-between border rounded px-3 py-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"text_pdf"}),e.jsxs("span",{className:"font-medium",children:["⥠",v.text_pdf,"%"]})]}),e.jsxs("div",{className:"flex justify-between border rounded px-3 py-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"scanned_pdf"}),e.jsxs("span",{className:"font-medium",children:["⥠",v.scanned_pdf,"%"]})]}),e.jsxs("div",{className:"flex justify-between border rounded px-3 py-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"mixed_pdf"}),e.jsxs("span",{className:"font-medium",children:["⥠",v.mixed_pdf,"%"]})]}),e.jsxs("div",{className:"flex justify-between border rounded px-3 py-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Date errors"}),e.jsxs("span",{className:"font-medium",children:["< ",v.dateErrorMax,"%"]})]})]})})]})]})}function _s(a){const l=Math.floor(a/36e5),m=Math.floor(a%36e5/6e4);return l===0?`${m}m`:`${l}h ${m}m`}function ye(a){return new Date(a).toISOString().slice(0,19).replace("T"," ")+" UTC"}function Fe(a){return a==null?"â":(a/1024/1024).toFixed(2)+" MB"}function Be(a){return a==null?"â":a<1e3?`${a}ms`:`${(a/1e3).toFixed(1)}s`}function lt(a){const l=Date.parse(a)-Date.now();return l<=0?"imminent":"in "+_s(l)}function it({status:a}){const l={ok:{label:"OK",cls:"bg-green-100 text-green-800 border-green-200",Icon:Z},warning:{label:"WARNING",cls:"bg-amber-100 text-amber-800 border-amber-200",Icon:ee},critical:{label:"CRITICAL",cls:"bg-red-100 text-red-800 border-red-200",Icon:ve},unknown:{label:"UNKNOWN",cls:"bg-gray-100 text-gray-600 border-gray-200",Icon:zs}}[a];return e.jsxs("span",{className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full border text-sm font-semibold ${l.cls}`,children:[e.jsx(l.Icon,{className:"h-4 w-4"}),l.label]})}function dt({result:a}){const l={ok:"bg-green-100 text-green-800",warning:"bg-amber-100 text-amber-800",critical:"bg-red-100 text-red-800"}[a];return e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-semibold uppercase ${l}`,children:a})}function ct({run:a}){const[l,m]=P.useState(!1),i=a.status==="success";return e.jsxs("div",{className:"relative flex flex-col items-center",children:[e.jsx("button",{className:`w-4 h-4 rounded-full border-2 hover:scale-125 transition-transform focus:outline-none ${i?"bg-green-400 border-green-600":"bg-red-400 border-red-600"}`,onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),"aria-label":`Backup ${a.status} at ${a.time}`}),l&&e.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 z-10 w-52 bg-gray-900 text-white text-xs rounded-md px-3 py-2 shadow-xl pointer-events-none",children:[e.jsx("div",{className:"font-medium mb-1",children:i?"â
success":"â failed"}),e.jsx("div",{className:"text-gray-300",children:ye(a.time)}),a.durationMs!=null&&e.jsxs("div",{children:["Duration: ",Be(a.durationMs)]}),a.sizeBytes!=null&&e.jsxs("div",{children:["Size: ",Fe(a.sizeBytes)]}),a.error&&e.jsx("div",{className:"text-red-300 mt-1 break-words",children:a.error.slice(0,120)})]})]})}function fe({label:a,value:l,color:m}){const i=m==="green"?"text-green-700 font-semibold":m==="amber"?"text-amber-700 font-semibold":m==="red"?"text-red-700 font-semibold":"text-gray-900 font-medium";return e.jsxs("div",{className:"flex flex-col gap-0.5 min-w-[140px]",children:[e.jsx("span",{className:"text-xs text-gray-500 uppercase tracking-wide",children:a}),e.jsx("span",{className:`text-sm ${i}`,children:l})]})}function me({label:a,value:l,ok:m,bad:i}){const r=i?"text-red-700 font-semibold":m===!0?"text-green-700":m===!1?"text-amber-700":"text-gray-700";return e.jsxs("div",{className:"flex items-center justify-between py-1 border-b border-gray-50 last:border-0",children:[e.jsx("span",{className:"text-xs text-gray-500",children:a}),e.jsx("span",{className:`text-xs font-medium ${r}`,children:l})]})}function vs(a){return a==="critical"?e.jsx(F,{variant:"destructive",children:"Critical"}):a==="warning"?e.jsx(F,{className:"bg-amber-100 text-amber-800 border-amber-300",children:"Warning"}):e.jsx(F,{className:"bg-green-100 text-green-800 border-green-300",children:"OK"})}function ot(a){return a==="paused"?e.jsx(F,{variant:"destructive",children:"PAUSED"}):a==="critical"?e.jsx(F,{className:"bg-red-100 text-red-800 border-red-300",children:"CRITICAL"}):a==="warning"?e.jsx(F,{className:"bg-amber-100 text-amber-800 border-amber-300",children:"WARNING"}):e.jsx(F,{className:"bg-green-100 text-green-800 border-green-300",children:"NORMAL"})}
33function xt(){var R,w,M,p,G,O,z,Q,le,B,ie,q,pe,ce;const a=be(),{toast:l}=je(),[m,i]=P.useState(!1),{data:r,isLoading:o,error:f,refetch:d}=U({queryKey:["/api/admin-x9k2p7/ai-usage/stats"],queryFn:te({on401:"returnNull"}),refetchInterval:6e4}),{data:h,refetch:v}=U({queryKey:["/api/admin-x9k2p7/ai-usage/queue"],queryFn:te({on401:"returnNull"}),refetchInterval:3e4}),{data:k,refetch:n}=U({queryKey:["/api/admin-x9k2p7/ai-usage/reset-pause/status"],queryFn:te({on401:"returnNull"}),enabled:m,staleTime:0}),b=ae({mutationFn:()=>re("/api/admin-x9k2p7/ai-usage/reset-pause","POST",{confirmed:!0}),onSuccess:()=>{i(!1),l({title:"AI pause cleared",description:"Degradation level reset to NORMAL. Cooldown is now active."}),a.invalidateQueries({queryKey:["/api/admin-x9k2p7/ai-usage/stats"]}),n()},onError:t=>{const C=(t==null?void 0:t.message)??"Reset failed";l({title:"Reset blocked",description:C,variant:"destructive"})}});if(o)return e.jsxs("div",{className:"space-y-4 mt-6",children:[e.jsx(Y,{className:"h-24 w-full"}),e.jsx(Y,{className:"h-48 w-full"}),e.jsx(Y,{className:"h-32 w-full"})]});if(f||!r)return e.jsx("div",{className:"mt-6 p-4 border border-red-200 rounded-lg bg-red-50 text-red-700 text-sm",children:"Failed to load AI usage stats. Ensure you are logged in as admin."});const j=r.daily,s=r.monthly,u=r.qualitySignals,D=r.degradationLevel,g=t=>`$${t.toFixed(4)}`,S=t=>t>=1e3?`${(t/1e3).toFixed(1)}s`:`${Math.round(t)}ms`,N=t=>new Date(t).toLocaleString("en-GB",{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}),H=Object.entries(r.killSwitches??{}).filter(([,t])=>t).map(([t])=>t);return e.jsxs("div",{className:"space-y-6 mt-6",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Ts,{className:"w-5 h-5 text-violet-600"})," AI Extraction Usage"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"gpt-4o-mini · input $0.15/1M · output $0.60/1M · auto-refreshes every 60s"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[D==="paused"&&e.jsx(_,{size:"sm",variant:"destructive",onClick:()=>i(!0),children:"Reset Pause"}),e.jsxs(_,{size:"sm",variant:"outline",onClick:()=>{d(),v()},children:[e.jsx(he,{className:"w-4 h-4 mr-1"})," Refresh"]})]})]}),e.jsx(ks,{open:m,onOpenChange:i,children:e.jsxs(Cs,{className:"max-w-md",children:[e.jsxs(Ss,{children:[e.jsxs(Rs,{className:"flex items-center gap-2 text-red-700",children:[e.jsx(we,{className:"w-5 h-5"})," Confirm: Reset AI Pause"]}),e.jsx(As,{className:"text-sm text-muted-foreground",children:"Review the current state before clearing the pause. This action has a cooldown â you cannot reset again immediately."})]}),k?e.jsxs("div",{className:"space-y-3 text-sm",children:[k.pauseReason&&e.jsxs("div",{className:"p-3 border border-amber-200 bg-amber-50 rounded-lg",children:[e.jsx("p",{className:"text-xs font-semibold text-amber-800 mb-1",children:"Pause reason"}),e.jsx("p",{className:"text-amber-900",children:k.pauseReason})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"p-2 border rounded-lg bg-muted/30",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Current spend (24h)"}),e.jsxs("p",{className:"font-semibold",children:["$",k.context.dailyCostUsd.toFixed(4)]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[k.context.spentPct,"% of limit"]})]}),e.jsxs("div",{className:"p-2 border rounded-lg bg-muted/30",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Projected daily spend"}),e.jsxs("p",{className:`font-semibold ${k.context.projectedDailySpendUsd>k.context.dailyLimitUsd?"text-red-600":""}`,children:["$",k.context.projectedDailySpendUsd.toFixed(4)]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["of $",k.context.dailyLimitUsd.toFixed(0)," limit"]})]})]}),k.context.projectedDailySpendUsd>k.context.dailyLimitUsd*.8&&e.jsxs("div",{className:"p-3 border border-red-200 bg-red-50 rounded-lg flex items-start gap-2",children:[e.jsx(ee,{className:"w-4 h-4 text-red-600 flex-shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-red-800 text-xs",children:[e.jsx("strong",{children:"This may exceed your budget."})," Projected spend is near or above the daily limit. Only reset if the underlying issue has been resolved."]})]}),k.canReset?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["After reset, a ",parseInt(Vs.AI_RESET_COOLDOWN_MINUTES??"30",10)||30,"-minute c
33ooldown will prevent another immediate reset."]}):e.jsxs("div",{className:"p-3 border border-orange-200 bg-orange-50 rounded-lg text-xs text-orange-800",children:[e.jsx("strong",{children:"Cooldown active."})," You must wait ",Math.ceil(k.cooldownRemainingMs/6e4)," more minute",Math.ceil(k.cooldownRemainingMs/6e4)!==1?"s":""," before resetting again."]})]}):e.jsx("div",{className:"h-24 flex items-center justify-center text-muted-foreground text-sm",children:"Loading contextâ¦"}),e.jsxs(Ds,{children:[e.jsx(_,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(_,{variant:"destructive",disabled:b.isPending||!(k!=null&&k.canReset),onClick:()=>b.mutate(),children:b.isPending?"Resettingâ¦":"Yes, Resume AI"})]})]})}),e.jsxs("div",{className:`flex items-start gap-3 p-4 border rounded-lg ${D==="paused"?"border-red-400 bg-red-50 text-red-900":D==="critical"?"border-red-300 bg-red-50 text-red-800":D==="warning"?"border-amber-300 bg-amber-50 text-amber-800":"border-green-300 bg-green-50 text-green-800"}`,children:[e.jsxs("div",{className:"flex-shrink-0 mt-0.5",children:[D==="paused"&&e.jsx(bs,{className:"w-5 h-5"}),D==="critical"&&e.jsx(we,{className:"w-5 h-5"}),D==="warning"&&e.jsx(ee,{className:"w-5 h-5"}),D==="normal"&&e.jsx($e,{className:"w-5 h-5"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-semibold text-sm",children:"System State:"}),ot(D)]}),e.jsxs("p",{className:"text-xs leading-relaxed",children:[D==="paused"&&"All new AI extraction is blocked. Users see a 'high demand' message. Click 'Reset Pause' to restore service once the budget/limit concern is resolved.",D==="critical"&&`Cost is at â¥${r.config.dailyCostCritical*.95|0}% of daily limit. Survival mode active â only Tier 1 tasks (core extraction, first-pass OCR) are running. Classification, summaries, and translations are paused.`,D==="warning"&&`Cost is approaching ${j.warningThreshold.toFixed(0)}% of daily limit. No user impact yet â monitor closely.`,D==="normal"&&"All AI features operating normally within budget limits."]}),H.length>0&&e.jsxs("p",{className:"text-xs mt-1 font-medium",children:["Kill switches active: ",H.map(t=>e.jsx(F,{variant:"destructive",className:"mr-1 text-xs",children:t},t))]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3",children:"AI Usage Today"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[{label:"Total calls",value:j.totalCalls,icon:e.jsx(Us,{className:"w-4 h-4 text-violet-500"})},{label:"Est. cost",value:g(j.estimatedCostUsd),icon:e.jsx(Gs,{className:"w-4 h-4 text-green-600"})},{label:"Failures",value:j.failedCalls,icon:e.jsx(ve,{className:"w-4 h-4 text-red-500"})},{label:"Rate limited",value:j.rateLimitedCalls,icon:e.jsx(we,{className:"w-4 h-4 text-amber-500"})},{label:"Quota errors",value:j.quotaExceededCalls,icon:e.jsx(bs,{className:"w-4 h-4 text-red-600"})},{label:"Timeouts",value:j.timeoutCalls,icon:e.jsx(Ae,{className:"w-4 h-4 text-orange-500"})},{label:"Avg latency",value:S(j.avgLatencyMs),icon:e.jsx(Re,{className:"w-4 h-4 text-blue-500"})},{label:"Budget status",value:vs(j.status),icon:e.jsx($e,{className:"w-4 h-4 text-gray-500"})}].map(({label:t,value:C,icon:se})=>e.jsxs("div",{className:"flex items-start gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx("div",{className:"mt-0.5",children:se}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:t}),e.jsx("p",{className:"text-sm font-semibold",children:C})]})]},t))})]}),j.byTaskType.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-2",children:"Top cost drivers (today)"}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{children:"Task type"}),e.jsx(x,{className:"text-right",children:"Calls"}),e.jsx(x,{className:"text-right",children:"Est. cost"}),e.jsx(x,{className:"text-right",children:"Kill switch"})]})}),e.jsx(V,{children:j.byTaskType.map(t=>e.jsxs(A,{children:[e.jsx(c,{children:e.jsx(F,{variant:"outline",className:"capitalize",children:t.taskType})}),e.jsx(c,{className:"text-right",children:t.calls}),e.jsx(c,{className:"text-right font-mono text-xs",children:g(t.costUsd)}),e.jsx(c,{className:"text-right",children:r.killSwitches[t.taskType]?e.jsx(F,{variant:"destructive",className:"text-xs",children:"Disabled"}):e.jsx(F,{variant:"outline",className:"text-xs text-green-700",children:"Active"})})]},t.taskType))})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1.5",children:["Kill switches: set ",e.jsx("span",{className:"font-mono",children:"AI_DISABLE_<TASKTYPE>=true"})," env var to disable a specific task type while keeping others running."]})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-2 flex items-center gap-2",children:["Extraction quality signals (last 24h)",(u==null?void 0:u.alert)&&e.jsx(F,{variant:"destructive",className:"text-xs",children:"Alert: partial rate ⥠20%"})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:[{label:"Total reports",value:(u==null?void 0:u.totalReports)??0},{label:"No content found",value:(u==null?void 0:u.noContentCount)??0},{label:"AI blocked",value:(u==null?void 0:u.aiBlockedCount)??0},{label:"Low confidence",value:(u==null?void 0:u.lowConfidenceCount)??0},{label:"Fallback failed",value:(u==null?void 0:u.fallbackFailedCount)??0},{label:"Partial/empty rate",value:e.jsxs("span",{className:u!=null&&u.alert?"text-red-600 font-semibold":"",children:[(u==null?void 0:u.partialRatePct)??0,"%"]})}].map(({label:t,value:C})=>e.jsxs("div",{className:"p-3 border rounded-lg bg-muted/30",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:t}),e.jsx("p",{className:"text-sm font-semibold",children:C})]},t))}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:'"Partial/empty rate" = (no_content + fallback_failed) / total. An alert fires when this exceeds 20% â the system is technically running but qual
33ity is degrading.'})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-2",children:"Extraction queue"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 mb-3",children:[{label:"Queued",value:String(((R=h==null?void 0:h.summary)==null?void 0:R.queued)??0),color:"text-blue-600"},{label:"Processing",value:String(((w=h==null?void 0:h.summary)==null?void 0:w.processing)??0),color:"text-violet-600"},{label:"Failed (24h)",value:String(((M=h==null?void 0:h.summary)==null?void 0:M.failed24h)??0),color:"text-red-600"},{label:"Complete (24h)",value:String(((p=h==null?void 0:h.summary)==null?void 0:p.complete24h)??0),color:"text-green-600"}].map(({label:t,value:C,color:se})=>e.jsxs("div",{className:"p-3 border rounded-lg bg-muted/30 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:t}),e.jsx("p",{className:`text-xl font-bold ${se}`,children:C})]},t))}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsxs("div",{className:"p-3 border rounded-lg bg-muted/20 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg processing time"}),e.jsx("p",{className:"text-sm font-semibold",children:((G=h==null?void 0:h.summary)==null?void 0:G.avgProcessingMs)!=null?S(h.summary.avgProcessingMs):"â"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"last 24h completed"})]}),e.jsxs("div",{className:"p-3 border rounded-lg bg-muted/20 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Oldest active job"}),e.jsx("p",{className:"text-sm font-semibold",children:((O=h==null?void 0:h.summary)==null?void 0:O.oldestJobAgeMs)!=null?S(h.summary.oldestJobAgeMs):"â"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"time in queue"})]}),e.jsxs("div",{className:`p-3 border rounded-lg text-center ${(((z=h==null?void 0:h.summary)==null?void 0:z.stuckJobCount)??0)>0?"border-red-300 bg-red-50":"bg-muted/20"}`,children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Stuck jobs"}),e.jsx("p",{className:`text-sm font-semibold ${(((Q=h==null?void 0:h.summary)==null?void 0:Q.stuckJobCount)??0)>0?"text-red-600":""}`,children:((le=h==null?void 0:h.summary)==null?void 0:le.stuckJobCount)??0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[">",((B=h==null?void 0:h.summary)==null?void 0:B.stuckThresholdMin)??15," min threshold"]})]})]}),((h==null?void 0:h.activeJobs)??[]).length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Active / pending jobs"}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{children:"Document"}),e.jsx(x,{children:"Status"}),e.jsx(x,{children:"Attempts"}),e.jsx(x,{children:"Queued at"})]})}),e.jsx(V,{children:h.activeJobs.map(t=>e.jsxs(A,{className:t.isStuck?"bg-red-50/50":"",children:[e.jsxs(c,{className:"text-xs max-w-[180px] truncate",children:[t.docName??t.id.slice(0,8),t.isStuck&&e.jsx("span",{className:"ml-1 text-red-600 font-semibold",children:"(stuck)"})]}),e.jsx(c,{children:e.jsx(F,{className:t.status==="processing"?"bg-violet-100 text-violet-800":"bg-blue-100 text-blue-800",children:t.status})}),e.jsx(c,{className:"text-xs text-center",children:t.attemptCount}),e.jsxs(c,{className:`text-xs whitespace-nowrap ${t.isStuck?"text-red-600 font-medium":"text-muted-foreground"}`,children:[S(t.ageMs)," ago"]})]},t.id))})]})})]}),((h==null?void 0:h.failedJobs)??[]).length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-red-600 mb-1",children:"Failed jobs (last 24h)"}),e.jsx("div",{className:"border border-red-200 rounded-lg overflow-hidden",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{children:"Document"}),e.jsx(x,{children:"Attempts"}),e.jsx(x,{children:"Error"}),e.jsx(x,{children:"Failed at"})]})}),e.jsx(V,{children:h.failedJobs.map(t=>e.jsxs(A,{className:"bg-red-50/30",children:[e.jsx(c,{className:"text-xs max-w-[180px] truncate",children:t.docName??t.id.slice(0,8)}),e.jsx(c,{className:"text-xs text-center",children:t.attemptCount}),e.jsx(c,{className:"text-xs text-red-700 max-w-[220px] truncate",children:t.error??"â"}),e.jsx(c,{className:"text-xs text-muted-foreground whitespace-nowrap",children:t.completedAt?N(t.completedAt):"â"})]},t.id))})]})})]}),!((ie=h==null?void 0:h.activeJobs)!=null&&ie.length)&&!((q=h==null?void 0:h.failedJobs)!=null&&q.length)&&e.jsxs("div",{className:"p-4 border rounded-lg bg-green-50 text-green-700 text-sm flex items-center gap-2",children:[e.jsx(Z,{className:"w-4 h-4"})," Queue clear â no active, pending, or recently failed jobs."]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-2",children:"Per-user rate limits"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"p-3 border rounded-lg bg-muted/30",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Max AI calls per user / hour"}),e.jsx("p",{className:"text-sm font-semibold",children:((pe=r.perUserLimits)==null?void 0:pe.callsPerHour)??20}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Env: ",e.jsx("span",{className:"font-mono",children:"AI_PER_USER_CALLS_PER_HOUR"})]})]}),e.jsxs("div",{className:"p-3 border rounded-lg bg-muted/30",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Max tokens per user / day"}),e.jsx("p",{className:"text-sm font-semibold",children:(((ce=r.perUserLimits)==null?void 0:ce.tokensPerDay)??2e5).toLocaleStr
33ing()}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Env: ",e.jsx("span",{className:"font-mono",children:"AI_PER_USER_TOKENS_PER_DAY"})]})]})]})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3 flex items-center gap-2",children:["AI Usage This Month ",vs(s.status)]}),s.projectedMonthEndCostUsd>=s.criticalThreshold&&e.jsxs("div",{className:"flex items-center gap-2 p-3 mb-3 border border-red-300 bg-red-50 rounded-lg text-sm text-red-800",children:[e.jsx(ee,{className:"w-4 h-4 flex-shrink-0"}),"Forecast alert: at current rate, month-end spend will reach ",e.jsxs("strong",{children:["Â $",s.projectedMonthEndCostUsd.toFixed(2),"Â "]})," â exceeding the $",s.criticalThreshold," critical threshold."]}),s.projectedMonthEndCostUsd>=s.warningThreshold&&s.projectedMonthEndCostUsd<s.criticalThreshold&&e.jsxs("div",{className:"flex items-center gap-2 p-3 mb-3 border border-amber-300 bg-amber-50 rounded-lg text-sm text-amber-800",children:[e.jsx(ee,{className:"w-4 h-4 flex-shrink-0"}),"Forecast: projected month-end cost is ",e.jsxs("strong",{children:["Â $",s.projectedMonthEndCostUsd.toFixed(2),"Â "]})," â approaching the $",s.warningThreshold," warning level."]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:[{label:"Total calls",value:s.totalCalls.toLocaleString()},{label:"Est. cost",value:g(s.estimatedCostUsd)},{label:"Projected month-end",value:g(s.projectedMonthEndCostUsd)},{label:"Warning threshold",value:`$${s.warningThreshold}`},{label:"Critical threshold",value:`$${s.criticalThreshold}`},{label:"Request limit",value:s.requestLimit.toLocaleString()}].map(({label:t,value:C})=>e.jsxs("div",{className:"p-3 border rounded-lg bg-muted/30",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:t}),e.jsx("p",{className:"text-sm font-semibold",children:C})]},t))})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-2",children:"Last 20 AI failures"}),r.recentFailures.length===0?e.jsxs("div",{className:"p-4 border rounded-lg bg-green-50 text-green-700 text-sm flex items-center gap-2",children:[e.jsx(Z,{className:"w-4 h-4"})," No failures recorded â all AI calls have succeeded."]}):e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{children:"Time"}),e.jsx(x,{children:"Task"}),e.jsx(x,{children:"Status"}),e.jsx(x,{children:"Error"}),e.jsx(x,{className:"text-right",children:"Latency"})]})}),e.jsx(V,{children:r.recentFailures.map(t=>e.jsxs(A,{children:[e.jsx(c,{className:"text-xs text-muted-foreground whitespace-nowrap",children:N(t.createdAt)}),e.jsx(c,{children:e.jsx(F,{variant:"outline",className:"capitalize text-xs",children:t.taskType})}),e.jsx(c,{children:e.jsx(F,{className:t.status==="quota_exceeded"?"bg-red-100 text-red-800":t.status==="rate_limited"?"bg-amber-100 text-amber-800":t.status==="timeout"?"bg-orange-100 text-orange-800":"bg-gray-100 text-gray-700",children:t.status.replace("_"," ")})}),e.jsxs(c,{className:"text-xs text-muted-foreground max-w-[240px] truncate",children:[t.errorCode&&e.jsxs("span",{className:"font-mono mr-1",children:["[",t.errorCode,"]"]}),t.errorMessageSafe??"â"]}),e.jsx(c,{className:"text-right text-xs",children:t.latencyMs!=null?S(t.latencyMs):"â"})]},t.id))})]})})]})]})}function mt({rate:a}){const l=Math.round(a*100),m=l>=99?"text-green-700":l>=95?"text-amber-700":"text-red-600";return e.jsxs("span",{className:`font-mono text-sm font-medium ${m}`,children:[l,"%"]})}function ut(){var ce;const{toast:a}=je(),l=new Date().toISOString().slice(0,10),m=new Date(Date.now()-7*864e5).toISOString().slice(0,10),[i,r]=P.useState(7),[o,f]=P.useState(m),[d,h]=P.useState(l),[v,k]=P.useState({start:m,end:l}),[n,b]=P.useState("qualified"),j=i==="custom"?`start=${v.start}&end=${v.end}`:`days=${i}`,{data:s,isLoading:u,error:D,refetch:g}=U({queryKey:["/api/admin-x9k2p7/bot-report/weekly",j],queryFn:async()=>(await re(`/api/admin-x9k2p7/bot-report/weekly?${j}`,"GET")).json(),refetchInterval:!1}),S=ae({mutationFn:()=>re("/api/admin-x9k2p7/bot-report/send-now","POST"),onSuccess:()=>a({title:"Email sent",description:"Weekly bot report dispatched to [email protected]"}),onError:()=>a({title:"Failed",description:"Could not send report email",variant:"destructive"})}),N=s?new Date(s.periodStart).toLocaleDateString("en-GB",{day:"numeric",month:"short"}):"â",H=s?new Date(s.periodEnd).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}):"â";
33if(u)return e.jsxs("div",{className:"space-y-4 mt-6",children:[e.jsx(Y,{className:"h-24 w-full"}),e.jsx(Y,{className:"h-48 w-full"}),e.jsx(Y,{className:"h-48 w-full"})]});if(D||!s)return e.jsx("div",{className:"mt-6 p-4 border border-red-200 rounded-lg bg-red-50 text-red-700 text-sm",children:"Failed to load bot report. Ensure you are logged in as admin and the table exists."});const R=t=>`${t.toFixed(1)}%`,w=t=>t.toLocaleString("en-GB"),M=t=>`${Math.round(t*100)}%`,p=t=>t?new Date(t).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}):"Not crawled",G=t=>t==="GREEN"?"bg-emerald-50 text-emerald-700 border-emerald-200":t==="AMBER"?"bg-amber-50 text-amber-700 border-amber-200":"bg-red-50 text-red-700 border-red-200",O=n==="qualified"||n==="ai"||n==="all",z=n==="qualified"||n==="all",Q=n==="google"||n==="all",le=n==="technical"||n==="all",B=n==="security"||n==="all",ie=s.technicalRequests.reduce((t,C)=>t+C.count,0),q=n==="technical"?[[w(ie),"Technical endpoint requests","excluded from GEO KPIs"],[w(s.technicalRequests.length),"Technical paths","distinct requested paths"]]:n==="security"?[[w(s.securityProbeStats.total),"Security probes","separate from GEO traffic"],[w(s.securityProbeStats.blocked),"Expected blocked","401, 403, or 404"],[w(s.securityProbeStats.successful),"Probe 2xx responses","requires security review"]]:n==="google"?[[w(s.qualifiedGooglebotCrawls),"Qualified Googlebot crawls","public content only"],[M(s.googlebotQualified2xxRate),"Qualified Googlebot 2xx","content success rate"]]:n==="all"?[[w(s.totals.botRequests),"All bot requests","raw operational total"],[w(s.rawAiCrawlerRequests),"Raw AI crawler requests","secondary operational metric"],[M(s.rawAi2xxRate),"Raw AI 2xx rate","all recognised AI requests"],[w(s.totals.uniqueUrls),"Unique paths","all classifications"]]:[[w(s.qualifiedAiContentCrawls),"Qualified AI content crawls","primary GEO KPI"],[M(s.qualifiedAi2xxRate),"Qualified content 2xx","content success rate"],[w(s.priorityPageDetails.filter(t=>t.totalQualifiedAiHits>0).length),"Priority pages reached",`of ${s.priorityPageDetails.length}`],[w(s.qualifiedGooglebotCrawls),"Qualified Googlebot",`${M(s.googlebotQualified2xxRate)} 2xx`]],pe=(t,C,se)=>e.jsxs(T,{children:[e.jsx($,{className:"pb-2",children:e.jsx(I,{className:"text-sm font-semibold",children:t})}),e.jsx(E,{className:"space-y-2",children:C.length===0?e.jsxs("p",{className:"text-sm text-emerald-700 flex items-center gap-2",children:[e.jsx(Z,{className:"h-4 w-4"}),se]}):C.map((oe,De)=>e.jsxs("div",{className:`rounded-md border p-2 text-xs ${oe.severity==="HIGH"?"border-red-200 bg-red-50 text-red-800":"border-amber-200 bg-amber-50 text-amber-800"}`,children:[e.jsx("span",{className:"font-semibold mr-2",children:oe.severity}),oe.message]},`${oe.code}-${De}`))})]});return e.jsxs("div",{className:"space-y-6 mt-6",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Is,{className:"h-5 w-5 text-slate-600"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Bot Crawl Report"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[N," â ",H," · ",s.rangeDays," day window"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("div",{role:"group","aria-label":"Report period",className:"flex rounded-md border bg-muted/30 p-0.5",children:[7,30,90].map(t=>e.jsxs("button",{type:"button",onClick:()=>r(t),"aria-pressed":i===t,className:`px-3 py-1.5 text-xs font-medium rounded-sm ${i===t?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:[t," days"]},t))}),e.jsxs(_,{size:"sm",variant:"outline",onClick:()=>g(),"aria-label":"Refresh bot report",children:[e.jsx(he,{className:"w-4 h-4 mr-1"}),"Refresh"]}),e.jsxs(_,{size:"sm",variant:"outline",onClick:()=>S.mutate(),disabled:S.isPending,children:[S.isPending?e.jsx(Ne,{className:"w-4 h-4 mr-1 animate-spin"}):e.jsx(Os,{className:"w-4 h-4 mr-1"}),"Send email now"]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border bg-muted/20 p-3 md:flex-row md:items-end",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("label",{className:"grid gap-1 text-xs font-medium",children:["Custom start",e.jsx("input",{type:"date",value:o,max:d||l,onChange:t=>f(t.target.value),className:"h-8 rounded-md border bg-background px-2 text-xs","aria-label":"Custom report start date"})]}),e.jsxs("label",{className:"grid gap-1 text-xs font-medium",children:["Custom end",e.jsx("input",{type:"date",value:d,min:o,max:l,onChange:t=>h(t.target.value),className:"h-8 rounded-md border bg-background px-2 text-xs","aria-label":"Custom report end date"})]})]}),e.jsx(_,{size:"sm",variant:i==="custom"?"default":"outline",disabled:!o||!d||o>d,onClick:()=>{k({start:o,end:d}),r("custom")},children:"Apply custom dates"})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b pb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Reporting view"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified content separates real discovery from infrastru
33cture noise."})]}),e.jsx("div",{role:"group","aria-label":"Traffic view",className:"flex flex-wrap rounded-md border p-0.5",children:[["qualified","Qualified Content"],["ai","AI Crawlers"],["google","Google"],["technical","Technical"],["security","Security Probes"],["all","All Recorded Bot Traffic"]].map(([t,C])=>e.jsx("button",{type:"button",onClick:()=>b(t),"aria-pressed":n===t,className:`px-3 py-1.5 text-xs rounded-sm ${n===t?"bg-slate-800 text-white":"text-muted-foreground"}`,children:C},t))})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-4",children:q.map(([t,C,se],oe)=>e.jsx(T,{className:oe===0?"border-slate-300 bg-slate-50/60":void 0,children:e.jsxs(E,{className:"pt-4 pb-3",children:[e.jsx("div",{className:"text-3xl font-bold text-slate-900",children:t}),e.jsx("div",{className:"text-xs font-semibold mt-1",children:C}),e.jsx("div",{className:"text-xs text-muted-foreground",children:se})]})},C))}),n==="all"&&e.jsxs(T,{className:"border-slate-200 bg-slate-50/50",children:[e.jsxs($,{className:"pb-2",children:[e.jsx(I,{className:"text-sm font-semibold",children:"All recorded traffic context"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This secondary view includes technical endpoints, security probes, and other non-content bot requests."})]}),e.jsx(E,{children:e.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-mono text-lg font-semibold",children:w(s.totals.botRequests)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"all bot requests"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-mono text-lg font-semibold",children:w(s.totals.uniqueBots)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"unique bots"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-mono text-lg font-semibold",children:w(s.totals.uniqueUrls)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"unique paths"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-mono text-lg font-semibold",children:w(s.totals.prerenderedHits)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"prerendered hits"})]})]})})]}),O&&e.jsxs(T,{children:[e.jsx($,{className:"pb-2",children:e.jsx(I,{className:"text-sm font-semibold",children:"Qualified crawler mix and change"})}),e.jsx(E,{children:e.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-5",children:[Object.entries(s.qualifiedCrawlerTotals).filter(([,t])=>t>0).map(([t,C])=>e.jsxs("div",{children:[e.jsx("div",{className:"font-mono text-lg font-semibold",children:w(C)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t})]},t)),e.jsxs("div",{children:[e.jsx("div",{className:"font-mono text-lg font-semibold",children:s.weekOverWeek.baselineState==="COMPARABLE"?`${(ce=s.weekOverWeek.qualifiedAiContentCrawlsPct)==null?void 0:ce.toFixed(1)}%`:"â"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"vs prior baseline"})]})]})})]}),O&&e.jsxs(T,{children:[e.jsxs($,{className:"pb-2",children:[e.jsx(I,{className:"text-sm font-semibold",children:"Priority page freshness"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified AI content crawls only. Freshness is based on days since the latest crawl."})]}),e.jsx(E,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{children:"Page"}),e.jsx(x,{children:"Last crawl"}),e.jsx(x,{children:"Crawlers"}),e.jsx(x,{className:"text-right",children:"Hits"}),e.jsx(x,{className:"text-right",children:"2xx"}),e.jsx(x,{className:"text-right",children:"Days since"}),e.jsx(x,{children:"Status"})]})}),e.jsx(V,{children:s.priorityPageDetails.map(t=>e.jsxs(A,{children:[e.jsx(c,{className:"font-mono text-xs whitespace-nowrap",children:t.path}),e.jsx(c,{className:"text-xs whitespace-nowrap",children:p(t.lastCrawled)}),e.jsx(c,{className:"text-xs text-muted-foreground whitespace-nowrap",children:t.crawlers.length?t.crawlers.join(", "):"â"}),e.jsx(c,{className:"text-right font-mono text-sm",children:w(t.totalQualifiedAiHits)}),e.jsx(c,{className:"text-right font-mono text-sm",children:M(t.httpSuccessRate)}),e.jsx(c,{className:"text-right font-mono text-sm",children:t.daysSinceLastAiCrawl??"â"}),e.jsx(c,{children:e.jsx("span",{className:`inline-flex rounded border px-2 py-0.5 text-[10px] font-semibold tracking-wide ${G(t.freshness)}`,children:t.freshness})})]},t.path))})]})})})]}),O&&e.jsxs("div",{className:"grid grid-cols-1 gap-4 xl:grid-cols-2",children:[e.jsxs(T,{children:[e.jsxs($,{className:"pb-2",children:[e.jsx(I,{className:"text-sm font-semibold",children:"Top qualified pages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Public content pages with qualified AI crawls. Technical and probe paths excluded."})]}),e.jsx(E,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{children:"Page"}),e.jsx(x,{className:"text-right",children:"Hits"}),e.jsx(x,{className:"text-right",children:"OAI"}),e.jsx(x,{className:"text-right",children:"ChatGPT"}),e.jsx(x,{className:"text-right",children:"2xx"})]})}),e.jsx(V,{children:s.topQualifiedPages.slice(0,10).map(t=>e.jsxs(A,{children:[e.jsx(c,{className:"font-mono text-xs whitespace-nowrap",children:t.path}),e.jsx(c,{className:"text-right font-mono text-sm font-semibold",children:w(t.totalAiHits)}),e.jsx(c,{className:"text-right font-mono text-sm",children:t.byBot["OAI-SearchBot"]??0}),e.jsx(c,{className:"text-right font-mono text-sm",children:t.byBot["ChatGPT-User"]??0}),e.jsx(c,{className:"text-right",children:e.jsx(mt,{rate:t.httpSuccessRate})})]},t.path))})]})})})]}),e.jsxs(T,{children:[e.jsx($,{className:"pb-2",children:e.jsx(I,{className:"text-sm font-semibold",children:"Topic clusters"})}),e.jsx(E,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{children:"Cluster"}),e.jsx(x,{className:"text-right",children:"Hits"}),e.jsx(x,{className:"text-right",children:"Pages"}),e.jsx(x,{className:"text-right",children:"Coverage"})]})}),e.jsx(V,{children:s.topicClusters.map(t=>e.jsxs(A,{children:[e.jsx(c,{className:"text-sm",children:t.cluster}),e.jsx(c,{className:"text-right font-mono text-sm",children:w(t.qualifiedAiHits)}),e.jsx(c,{className:"text-right font-mono text-sm",children:t.uniquePagesCrawled}
33),e.jsx(c,{className:"text-right font-mono text-sm",children:R(t.coveragePct)})]},t.cluster))})]})})})]})]}),z&&e.jsxs(T,{children:[e.jsxs($,{className:"pb-2",children:[e.jsx(I,{className:"text-sm font-semibold",children:"Citation and mention reporting"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"These measures require external observation and are not inferred from server crawl logs."})]}),e.jsx(E,{children:e.jsx("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-3",children:Object.entries(s.visibility).map(([t,C])=>e.jsxs("div",{className:"rounded-md border bg-muted/20 p-3",children:[e.jsx("div",{className:"text-xs capitalize text-muted-foreground",children:t.replace(/[A-Z]/g,se=>` ${se}`)}),e.jsx("div",{className:"mt-1 text-sm font-medium",children:C})]},t))})})]}),(le||B)&&e.jsxs("div",{className:"grid grid-cols-1 gap-4 xl:grid-cols-2",children:[le&&e.jsxs(T,{children:[e.jsxs($,{className:"pb-2",children:[e.jsx(I,{className:"text-sm font-semibold",children:"Technical endpoint requests"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Infrastructure traffic is reported separately from content discovery."})]}),e.jsx(E,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{children:"Path"}),e.jsx(x,{className:"text-right",children:"Requests"})]})}),e.jsx(V,{children:s.technicalRequests.length?s.technicalRequests.slice(0,12).map(t=>e.jsxs(A,{children:[e.jsx(c,{className:"font-mono text-xs",children:t.path}),e.jsx(c,{className:"text-right font-mono text-sm",children:w(t.count)})]},t.path)):e.jsx(A,{children:e.jsx(c,{colSpan:2,className:"text-sm text-muted-foreground",children:"No technical endpoint requests recorded."})})})]})})})]}),B&&e.jsxs(T,{className:"border-amber-200",children:[e.jsxs($,{className:"pb-2",children:[e.jsxs(I,{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(ys,{className:"h-4 w-4 text-amber-600"}),"Security probes"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Blocked 401, 403, and 404 probes are expected internet background noise, not crawl errors."})]}),e.jsxs(E,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-mono text-xl font-semibold",children:w(s.securityProbeStats.total)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"total"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-mono text-xl font-semibold text-amber-700",children:w(s.securityProbeStats.blocked)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"blocked"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-mono text-xl font-semibold",children:w(s.securityProbeStats.successful)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"successful"})]})]}),e.jsx("div",{className:"space-y-1",children:s.securityProbeStats.byPath.slice(0,7).map(t=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("code",{children:t.path}),e.jsxs("span",{className:"font-mono",children:[t.count," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",t.blocked," blocked)"]})]})]},t.path))})]})]})]}),O&&e.jsxs("div",{className:"grid grid-cols-1 gap-4 xl:grid-cols-2",children:[e.jsxs(T,{children:[e.jsxs($,{className:"pb-2",children:[e.jsx(I,{className:"text-sm font-semibold",children:"Content crawl errors"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified AI or search bots receiving 4xx/5xx on public content. Probe responses are excluded."})]}),e.jsx(E,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{children:"Bot"}),e.jsx(x,{children:"Path"}),e.jsx(x,{className:"text-right",children:"Status"}),e.jsx(x,{className:"text-right",children:"Count"})]})}),e.jsx(V,{children:s.contentCrawlErrors.length?s.contentCrawlErrors.map((t,C)=>e.jsxs(A,{children:[e.jsx(c,{children:t.botName}),e.jsx(c,{className:"font-mono text-xs",children:t.path}),e.jsx(c,{className:"text-right font-mono",children:t.statusCode}),e.jsx(c,{className:"text-right font-mono",children:t.count})]},`${t.path}-${C}`)):e.jsx(A,{children:e.jsx(c,{colSpan:4,className:"text-sm text-emerald-700",children:"No qualified content crawl errors recorded."})})})]})})})]}),pe("GEO anomalies",s.geoAnomalies,"No qualified content anomalies detected.")]}),B&&pe("Security anomalies",s.securityAnomalies,"No security anomalies detected."),Q&&e.jsxs(T,{children:[e.jsxs($,{className:"pb-2",children:[e.jsx(I,{className:"text-sm font-semibold",children:"Google qualified content"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Googlebot activity on public content only. Technical and probe requests are excluded."})]}),e.jsxs(E,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-mono text-2xl font-semibold",children:w(s.qualifiedGooglebotCrawls)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"qualified Googlebot crawls"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-mono text-2xl font-semibold",children:M(s.googlebotQualified2xxRate)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"qualified 2xx rate"})]})]}),s.contentCrawlErrors.filter(t=>t.botName==="Googlebot").length>0&&e.jsx("div",{className:"mt-4 space-y-1 text-xs",children:s.contentCrawlErrors.filter(t=>t.botName==="Googlebot").map((t,C)=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("code",{children:t.path}),e.jsxs("span",{className:"font-mono",children:[t.statusCode," · ",t.count]})]},`${t.path}-${C}`))})]})]}),(O||Q)&&s.trendHistory.length>0&&e.jsxs(T,{children:[e.jsxs($,{className:"pb-2",children:[e.jsxs(I,{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(qe,{className:"h-4 w-4"}),"Trend history"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Legacy rows captured before qualified classification are marked non-comparable."})]}),e.jsx(E,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{children:"Week"}),e.jsx(x,{className:"text-right",children:"Qualified crawls"}),e.jsx(x,{className:"text-right",children:"OAI"}),e.jsx(x,{className:"text-right",children:"ChatGPT"}),e.jsx(x,{className:"text-right",children:"Googlebot"}),e.jsx(x,{className:"text-right",children:"2xx"}),e.jsx(x,{className:"text-right",children:"Priority coverage"})]})}),e.jsx(V,{children:s.trendHistory.map(t=>{const C=t.qualifiedMetricsAvailable===!0;return e.jsxs(A,{children:[e.jsxs(c,{className:"text-xs",children:[p(t.weekStart),!C&&e.jsx("span",{className:"ml-2 text-[10px] text-muted-foreground",children:"non-comparable"})]}),e.jsx(c,{className:"text-right font-mono",children:C?t.qualifiedAiHits:"N/A"}),e.jsx(c,{className:"text-right font-mono",children:C?t.oaiQualified:"N/A"}),e.jsx(c,{className:"text-right font-mono",children:C?t.chatgptQualified:"N/A"}),e.jsx(c,{className:"text-right font-mono",children:C?t.googlebotQualified:"N/A"}),e.jsx(c,{className:"text-right font-mono",children:C&&t.qualifiedAi2xxRate!=null?M(t.qualifiedAi2xxRate):"N/A"}),e.jsx(c,{className:"text-right font-mono",children:C&&t.priorityCoveragePct!=null?`${t.priorityCoveragePct.toFixed(1)}%`:"N/A"})]},t.weekStart)})})]})})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Bot logging is active in production only. Qualified content means recognised AI crawler requests to public PRIVAWELL content pages; raw traffic includes technical and other non-content requests. Citation and mention metrics are not inferred from crawl activity."})]})}function ht(){var j,s,u,D,g,S,N,H;const{toast:a}=je(),l=be(),[m,i]=P.useState(null),{data:r,isLoading:o,isError:f,dataUpdatedAt:d,refetch:h,isFetching:v}=U({queryKey:["/api/admin-x9k2p7/backup/status"],refetchInterval:3e4,staleTime:1e4,queryFn:te({on401:"returnNull"})}),k=ae({mutationFn:()=>re("/api/admin-x9k2p7/backup/run","POST"),onMutate:()=>i(null),onSuccess:async R=>{const M=(await R.json().catch(()=>({}))).message??"Backup completed.";i({ok:!0,msg:M}),a({title:"Backup triggered",description:M}
33),l.invalidateQueries({queryKey:["/api/admin-x9k2p7/backup/status"]})},onError:R=>{const w=(R==null?void 0:R.message)??"Backup failed â check logs.";i({ok:!1,msg:w}),a({title:"Backup failed",description:w,variant:"destructive"})}}),n=((j=r==null?void 0:r.env)==null?void 0:j.environment)==="production"||window.location.hostname==="admin.privawell.net",b=d?ye(new Date(d).toISOString()):"â";return e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-gray-400",children:["Auto-refreshes every 30s · Last: ",b]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(_,{variant:"outline",size:"sm",onClick:()=>h(),disabled:v,className:"gap-1.5",children:[e.jsx(he,{className:`h-3.5 w-3.5 ${v?"animate-spin":""}`}),"Refresh"]}),n?e.jsxs(_,{size:"sm",onClick:()=>k.mutate(),disabled:k.isPending,className:"gap-1.5 bg-amber-600 hover:bg-amber-700 text-white",children:[e.jsx(Pe,{className:`h-3.5 w-3.5 ${k.isPending?"animate-pulse":""}`}),k.isPending?"Runningâ¦":"Run Backup Now"]}):e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-gray-100 border border-gray-200 text-xs text-gray-400 select-none",children:[e.jsx(Pe,{className:"h-3.5 w-3.5"}),"Run Backup Now â production only"]})]})]}),m&&e.jsxs("div",{className:`rounded-lg px-4 py-3 text-sm font-medium border ${m.ok?"bg-green-50 border-green-200 text-green-800":"bg-red-50 border-red-200 text-red-800"}`,children:[m.ok?"â
":"â ",m.msg]}),o&&e.jsx("div",{className:"py-12 text-center text-gray-400",children:"Loading backup statusâ¦"}),f&&e.jsx("div",{className:"py-12 text-center text-red-500",children:"Failed to load â check admin session."}),!o&&!f&&!r&&e.jsx("div",{className:"py-12 text-center text-gray-400",children:"No backup data found."}),r&&e.jsxs(e.Fragment,{children:[e.jsxs(T,{className:"border-gray-200",children:[e.jsx($,{className:"pb-3",children:e.jsxs(I,{className:"text-sm flex items-center gap-2",children:[e.jsx(ys,{className:"h-4 w-4 text-amber-600"})," Current Status"]})}),e.jsx(E,{children:e.jsxs("div",{className:"flex flex-wrap gap-6",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-gray-500 uppercase tracking-wide",children:"Overall"}),e.jsx(it,{status:r.status})]}),e.jsx(fe,{label:"Last successful backup",value:(s=r.recentRuns.find(R=>R.status==="success"))!=null&&s.time?ye(r.recentRuns.find(R=>R.status==="success").time):(u=r.lastBackup)!=null&&u.success?r.lastBackup.timestamp+" (approx)":"No backup recorded"}),e.jsx(fe,{label:"Age",value:r.ageMs!=null?_s(r.ageMs):(D=r.lastBackup)!=null&&D.success?"< 1 process restart":"â",color:r.ageMs!=null?r.ageMs>=72e6?"red":r.ageMs>=504e5?"amber":"green":void 0}),e.jsx(fe,{label:"Next scheduled run",value:r.nextCronRunAt?ye(r.nextCronRunAt):"Not scheduled yet"}),e.jsx(fe,{label:"Time until next run",value:r.nextCronRunAt?lt(r.nextCronRunAt):"â"}),e.jsx(fe,{label:"Last duration",value:Be(((g=r.recentRuns[0])==null?void 0:g.durationMs)??((S=r.lastBackup)==null?void 0:S.durationMs))}),e.jsx(fe,{label:"Backup size",value:Fe(((N=r.recentRuns.find(R=>R.status==="success"))==null?void 0:N.sizeBytes)??((H=r.lastBackup)==null?void 0:H.sizeBytes))}),e.jsx(fe,{label:"Scheduler",value:r.schedulerRunning?"Active (cron)":r.env.schedulerEnabled?"Registered":"Disabled",color:r.env.schedulerEnabled?void 0:"amber"})]})})]}),e.jsxs(T,{className:"border-gray-200",children:[e.jsx($,{className:"pb-3",children:e.jsxs(I,{className:"text-sm flex items-center gap-2",children:[e.jsx(Ae,{className:"h-4 w-4 text-amber-600"})," Run Timeline (last ",r.recentRuns.length,")"]})}),e.jsx(E,{children:r.recentRuns.length===0?e.jsx("p",{className:"text-sm text-gray-400",children:"Runs appear here after the first backup completes in this process."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsx("div",{className:"flex items-end gap-3 min-w-max pb-2 pt-8",children:[...r.recentRuns].reverse().map((R,w)=>e.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[e.jsx(ct,{run:R}),e.jsx("span",{className:"text-[10px] text-gray-400 whitespace-nowrap",children:new Date(R.time).toISOString().slice(11,16)})]},w))})}),e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-xs text-gray-400",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-400 inline-block"}),"success"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-400 inline-block"}),"failed"]}),e.jsx("span",{children:"Hover dot for details · oldest â newest"})]})]})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-5",children:[e.jsxs(T,{className:"border-gray-200",children:[e.jsx($,{className:"pb-3",children:e.jsxs(I,{className:"text-sm flex items-center gap-2",children:[e.jsx(Z,{className:"h-4 w-4 text-amber-600"})," Sanity Check"]})}),e.jsxs(E,{className:"space-y-3",children:[e.jsx("div",{className:"space-y-1.5",children:[["OK","< 14h","bg-green-100 text-green-700"],["WARNING","14â20h","bg-amber-100 text-amber-700"],["CRITICAL","⥠20h","bg-red-100 text-red-700"]].map(([R,w,M])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-xs font-semibold px-2 py-0.5 rounded ${M}`,children:R}),e.jsx("span",{className:"text-xs text-gray-400",children:w})]},R))}),e.jsxs("div",{className:"border-t border-gray-100 pt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-gray-500",children:"Last check"}),e.jsx("span",{className:"text-xs font-medium text-gray-900",children:r.lastSanityCheck?ye(r.lastSanityCheck.checkedAt):"Not yet run"})]}),r.lastSanityCheck&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-gray-500",children:"Result"}),e.jsx(dt,{result:r.lastSanityCheck.result})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-gray-500",children:"Age at check"}),e.jsx("span",{className:"text-xs font-medium text-gray-900",children:r.lastSanityCheck.ageHours>=0?`${r.lastSanityCheck.ageHours.toFixed(1)}h`:"unknown"})]})]}),!r.lastSanityCheck&&e.jsx("p",{className:"text-xs text-gray-400",children:"First check runs 6h after startup (production only)."})]})]})]}),e.jsxs(T,{className:"border-gray-200",children:[e.jsx($,{className:"pb-3",children:e.jsxs(I,{className:"text-sm flex items-center gap-2",children:[e.jsx(Js,{className:"h-4 w-4 text-amber-600"}
33)," Environment Safety"]})}),e.jsxs(E,{className:"space-y-0",children:[e.jsx(me,{label:"Environment",value:r.env.environment}),e.jsx(me,{label:"Scheduler",value:r.env.schedulerEnabled?"ENABLED":"DISABLED",ok:r.env.schedulerEnabled,bad:!r.env.schedulerEnabled&&r.env.environment==="production"}),e.jsx(me,{label:"DISABLE_BACKUP_SCHEDULER",value:r.env.disableFlag,ok:r.env.disableFlag!=="true"}),e.jsx(me,{label:"Target bucket",value:r.env.bucket}),e.jsx(me,{label:"Env â bucket match",value:r.env.envMatch?"â
match":"â MISMATCH",ok:r.env.envMatch,bad:!r.env.envMatch}),e.jsx(me,{label:"Encryption",value:r.encryptionConfigured?"Configured":"Not configured",ok:r.encryptionConfigured}),e.jsx(me,{label:"S3 client",value:r.s3Configured?"Connected":"Not configured",ok:r.s3Configured}),e.jsx(me,{label:"DB host",value:r.dbHostInfo.host}),e.jsx(me,{label:"DB source",value:r.dbHostInfo.source})]})]})]}),e.jsxs(T,{className:"border-gray-200",children:[e.jsx($,{className:"pb-3",children:e.jsxs(I,{className:"text-sm flex items-center gap-2",children:[e.jsx(Ie,{className:"h-4 w-4 text-amber-600"})," Execution Log"]})}),e.jsx(E,{className:"p-0",children:r.recentRuns.length===0?e.jsx("p",{className:"px-6 py-4 text-sm text-gray-400",children:"No runs recorded in this process yet."}):e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{className:"bg-gray-50",children:[e.jsx(x,{className:"text-xs",children:"Time (UTC)"}),e.jsx(x,{className:"text-xs",children:"Status"}),e.jsx(x,{className:"text-xs",children:"Duration"}),e.jsx(x,{className:"text-xs",children:"Size"}),e.jsx(x,{className:"text-xs",children:"Notes"})]})}),e.jsx(V,{children:r.recentRuns.map((R,w)=>e.jsxs(A,{className:R.status==="failed"?"bg-red-50":void 0,children:[e.jsx(c,{className:"text-xs font-mono text-gray-700",children:ye(R.time)}),e.jsx(c,{children:R.status==="success"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-green-700 font-medium",children:[e.jsx(Z,{className:"h-3.5 w-3.5"}),"success"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-red-700 font-medium",children:[e.jsx(ve,{className:"h-3.5 w-3.5"}),"failed"]})}),e.jsx(c,{className:"text-xs text-gray-600",children:Be(R.durationMs)}),e.jsx(c,{className:"text-xs text-gray-600",children:Fe(R.sizeBytes)}),e.jsx(c,{className:"text-xs text-gray-500 max-w-xs truncate",children:R.error??""})]},w))})]})})]})]})]})}function L({label:a,value:l,sub:m}){return e.jsxs("div",{className:"border rounded-lg p-4 bg-card",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:a}),e.jsx("p",{className:"text-2xl font-bold tabular-nums",children:l}),m&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:m})]})}function ge({children:a}){return e.jsx("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide mt-6 mb-3",children:a})}function pt(){const[a,l]=P.useState("7d"),m=U({queryKey:["/api/admin-x9k2p7/retail-funnel/stats",a],queryFn:()=>fetch(`/api/admin-x9k2p7/retail-funnel/stats?period=${a}`,{credentials:"include"}).then(o=>o.json()),staleTime:6e4}),i=m.data,r=o=>o==="active"?e.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 font-medium",children:"active"}):o==="trialing"?e.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 font-medium",children:"trial"}):o==="canceled"?e.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300 font-medium",children:"canceled"}):e.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 font-medium",children:o});return e.jsxs("div",{className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(qe,{className:"w-5 h-5 text-amber-500"}),e.jsx("span",{className:"font-semibold text-base",children:"Retail Funnel Metrics"}),e.jsx("div",{className:"ml-auto flex gap-1",children:["today","7d","30d","all"].map(o=>e.jsx("button",{type:"button",onClick:()=>l(o),className:`px-3 py-1 text-xs font-medium rounded border transition-colors ${a===o?"bg-amber-500 text-white border-amber-500":"border-border text-muted-foreground hover:text-foreground bg-transparent"}`,children:o==="all"?"All time":o==="today"?"Today":o},o))})]}),m.isLoading&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:8}).map((o,f)=>e.jsx(Y,{className:"h-20 rounded-lg"},f))}),m.isError&&e.jsx("div",{className:"rounded-lg border border-red-300 bg-red-50 dark:bg-red-950 p-4 text-sm text-red-700 dark:text-red-300",children:"Failed to load funnel stats. Check server logs."}),i&&e.jsxs(e.Fragment,{children:[e.jsx(ge,{children:"Acquisition"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsx(L,{label:"Try-free page views",value:i.acquisition.tryFreeViews}),e.jsx(L,{label:"CTA clicks (click_start_free)",value:i.acquisition.startFreeClicks}),e.jsx(L,{label:"CTA conversion rate",value:i.acquisition.cta_conv_rate,sub:"views â clicks"})]}),e.jsx(ge,{children:"Activation"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(L,{label:"Vaults created",value:i.activation.vaultsCreated,sub:"vault_created event"}),e.jsx(L,{label:"Uploads started",value:i.activation.uploadStarted}),e.jsx(L,{label:"Uploads completed",value:i.activation.uploadCompleted,sub:i.activation.upload_completion_rate+" completion"}),e.jsx(L,{label:"Extraction success rate",value:i.activation.extraction_success_rate,sub:`${i.activation.extractionCompleted} ok / ${i.activation.extractionFailed} failed`}),e.jsx(L,{label:"Manual entry opened",value:i.activation.manualEntryOpened}),e.jsx(L,{label:"Manual entry saved",value:i.activation.manualEntrySaved})]}),e.jsx(ge,{children:"Value Realisation"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsx(L,{label:"Summary viewed",value:i.value.summaryViewed}),e.jsx(L,{label:"Export clicked",value:i.value.exportClicked})]}),e.jsx(ge,{children:"Paywall & Checkout"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(L,{label:"Paywall shown",value:i.paywall.paywallShown}),e.jsx(L,{label:"Checkout started",value:i.paywall.checkoutStarted,sub:i.paywall.shown_to_started_rate+" of shown"}),e.jsx(L,{label:"Checkout completed",value:i.paywall.checkoutCompleted,sub:i.paywall.checkout_conv_rate+" of started"})]}),e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsx("div",{className:"px-4 py-2 bg-muted/40 text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"Paywall trigger breakdown"}),e.jsx("div",{className:"grid grid-cols-4 divide-x text-center",children:Object.entries(i.paywall.triggerBreakdown).map(([o,f])=>e.jsxs("div",{className:"py-4",children:[e.jsx("p",{className:"text-lg font-bold tabular-nums",children:f}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:o})]},o))})]}),e.jsx(ge,{children:"Revenue"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(L,{label:"New users in period",value:i.revenue.newUsersInPeriod}),e.jsx(L,{label:"Active",value:i.revenue.newActive,sub:"subscription_status = active"}),e.jsx(L,{label:"Trialing",value:i.revenue.newTrialing,sub:"subscription_status = trialing"}),e.jsx(L,{label:"Canceled",value:i.revenue.newCanceled,sub:"subscription_status = canceled"}),e.jsx(L,{label:"No status yet",value:i.revenue.newNone,sub:"null â awaiting webhook"}),e.jsx(L,{label:"Trial â active rate",value:i.revenue.trial_to_active_rate})]}),e.jsxs("div",{className:`rounded-lg border px-4 py-3 text-sm flex items-start gap-2 mt-2 ${i.revenue.stripeUnlinked>
330?"border-amber-300 bg-amber-50 dark:bg-amber-950 dark:border-amber-700 text-amber-800 dark:text-amber-200":"border-green-300 bg-green-50 dark:bg-green-950 dark:border-green-700 text-green-800 dark:text-green-200"}`,children:[e.jsx("span",{className:"shrink-0 mt-0.5",children:i.revenue.stripeUnlinked>0?"â ï¸":"â"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Stripe reconciliation (all-time):"})," ",i.revenue.stripeUnlinked>0?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:i.revenue.stripeUnlinked})," user(s) with a Stripe customer ID have no ",e.jsx("code",{className:"font-mono text-xs",children:"subscription_status"})," â possible webhook lag or provisioning gap. Check Provisioning Incidents tab."]}):"All Stripe-linked users have a subscription_status set â no gaps detected."]})]}),e.jsx(ge,{children:"Step-by-step Funnel"}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{children:"Step"}),e.jsx(x,{className:"text-right",children:"Count"}),e.jsx(x,{className:"text-right",children:"Step drop-off"}),e.jsx(x,{className:"text-right",children:"% of top"})]})}),e.jsx(V,{children:i.funnelTable.map((o,f)=>e.jsxs(A,{children:[e.jsx(c,{className:"text-sm",children:o.step}),e.jsx(c,{className:"text-right font-mono text-sm",children:o.count.toLocaleString()}),e.jsx(c,{className:"text-right text-sm",children:o.stepDropoff!==null?e.jsxs("span",{className:"flex items-center justify-end gap-1 text-red-500 dark:text-red-400",children:[e.jsx(Qs,{className:"w-3 h-3"})," ",o.stepDropoff]}):e.jsx("span",{className:"text-muted-foreground",children:"â"})}),e.jsx(c,{className:"text-right text-sm text-muted-foreground",children:o.totalDropoff})]},f))})]})}),i.failureReasons.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(ge,{children:"Extraction Failure Reasons"}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{children:"Reason"}),e.jsx(x,{className:"text-right",children:"Count"})]})}),e.jsx(V,{children:i.failureReasons.map((o,f)=>e.jsxs(A,{children:[e.jsx(c,{className:"text-sm font-mono",children:o.reason}),e.jsx(c,{className:"text-right text-sm",children:o.count})]},f))})]})})]}),e.jsx(ge,{children:"Recent Users Cohort"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-2 mb-3",children:"All users created in period â track trial â active progression. Stripe-linked = customer ID present in DB."}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{children:"Email (masked)"}),e.jsx(x,{children:"Status"}),e.jsx(x,{children:"Plan"}),e.jsx(x,{className:"text-center",children:"Stripe"}),e.jsx(x,{className:"text-right",children:"Docs"}),e.jsx(x,{className:"text-right",children:"Joined"})]})}),e.jsxs(V,{children:[i.recentTrialUsers.length===0&&e.jsx(A,{children:e.jsx(c,{colSpan:6,className:"text-center text-sm text-muted-foreground py-6",children:"No users in this period."})}),i.recentTrialUsers.map((o,f)=>e.jsxs(A,{children:[e.jsx(c,{className:"font-mono text-sm",children:o.email}),e.jsx(c,{children:r(o.status)}),e.jsx(c,{className:"text-sm text-muted-foreground",children:o.plan}),e.jsx(c,{className:"text-center text-sm",children:o.stripeLinked?e.jsx("span",{className:"text-green-600 dark:text-green-400",title:"Stripe customer ID present",children:"â"}):e.jsx("span",{className:"text-muted-foreground",title:"No Stripe customer ID",children:"â"})}),e.jsx(c,{className:"text-right text-sm",children:o.docs}),e.jsx(c,{className:"text-right text-xs text-muted-foreground",children:new Date(o.createdAt).toLocaleDateString()})]},f))]})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Last refreshed: ",new Date(i.periodEnd).toLocaleString()," · Events sourced from ",e.jsx("code",{className:"font-mono",children:"user_analytics"})," table ·"," ",i.periodStart?`Period: ${new Date(i.periodStart).toLocaleDateString()} â now`:"All time"]})]})]})}function gt(){var i;const a=be(),l=U({queryKey:["/api/admin-x9k2p7/dob-repair-no-evidence"],queryFn:()=>fetch("/api/admin-x9k2p7/dob-repair-no-evidence",{credentials:"include"}).then(r=>r.json()),staleTime:6e4}),m=((i=l.data)==null?void 0:i.rows)??[];return e.jsxs("div",{className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Oe,{className:"w-5 h-5 text-orange-500"}),e.jsx("span",{className:"font-semibold text-base",children:"DOB Repair â No Evidence"}),e.jsx(F,{variant:"outline",className:"ml-1 text-orange-700 border-orange-300 bg-orange-50 dark:bg-orange-950 dar
33k:text-orange-300",children:l.isLoading?"â¦":m.length}),e.jsx(_,{variant:"ghost",size:"sm",className:"ml-auto",onClick:()=>a.invalidateQueries({queryKey:["/api/admin-x9k2p7/dob-repair-no-evidence"]}),children:e.jsx(he,{className:`w-4 h-4 ${l.isFetching?"animate-spin":""}`})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["These audit entries were written when ",e.jsx("code",{className:"text-xs bg-muted px-1 rounded",children:"repairDobPoisonedEvents"})," found canonical events flagged as DOB-poisoned but could not locate a backing vault document to re-process. The affected events remain in ",e.jsx("span",{className:"font-medium text-amber-600 dark:text-amber-400",children:"needs_review"})," and require manual investigation."]}),l.isLoading&&e.jsx("div",{className:"space-y-2",children:[1,2,3].map(r=>e.jsx(Y,{className:"h-10 w-full"},r))}),!l.isLoading&&m.length===0&&e.jsxs("div",{className:"flex flex-col items-center gap-2 py-12 text-muted-foreground",children:[e.jsx(Z,{className:"w-8 h-8 text-green-400"}),e.jsx("span",{className:"text-sm",children:"No DOB_REPAIR_NO_EVIDENCE entries found."})]}),m.length>0&&e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{className:"w-[160px]",children:"Timestamp"}),e.jsx(x,{children:"User ID"}),e.jsx(x,{children:"Family Member ID"}),e.jsx(x,{children:"DOB"}),e.jsx(x,{children:"Stuck Event IDs"}),e.jsx(x,{children:"Note"})]})}),e.jsx(V,{children:m.map(r=>{const o=r.metadata??{},f=Array.isArray(o.flaggedEventIds)?o.flaggedEventIds:[];return e.jsxs(A,{children:[e.jsx(c,{className:"text-xs text-muted-foreground whitespace-nowrap",children:new Date(r.timestamp).toLocaleString()}),e.jsxs(c,{className:"font-mono text-xs",children:[r.userId.slice(0,8),"â¦"]}),e.jsx(c,{className:"font-mono text-xs",children:o.familyMemberId?`${o.familyMemberId.slice(0,8)}â¦`:"â"}),e.jsx(c,{className:"font-mono text-xs",children:o.dob??"â"}),e.jsx(c,{children:f.length===0?e.jsx("span",{className:"text-muted-foreground text-xs",children:"â"}):e.jsx("div",{className:"flex flex-wrap gap-1",children:f.map(d=>e.jsxs(F,{variant:"outline",className:"font-mono text-xs px-1 py-0",children:[d.slice(0,8),"â¦"]},d))})}),e.jsx(c,{className:"text-xs max-w-[280px] truncate text-muted-foreground",title:o.note??"",children:o.note??"â"})]},r.id)})})]})})]})}function jt(){var u,D;const a=be(),{toast:l}=je(),[m,i]=P.useState(null),[r,o]=P.useState("resolved"),[f,d]=P.useState(""),h=U({queryKey:["/api/admin-x9k2p7/reconciliation"],queryFn:()=>fetch("/api/admin-x9k2p7/reconciliation",{credentials:"include"}).then(g=>g.json()),staleTime:3e4}),v=U({queryKey:["/api/admin-x9k2p7/reconciliation/health"],queryFn:()=>fetch("/api/admin-x9k2p7/reconciliation/health",{credentials:"include"}).then(g=>g.json()),staleTime:3e4}),k=ae({mutationFn:({id:g,status:S,note:N})=>fetch(`/api/admin-x9k2p7/reconciliation/reviews/${g}/resolve`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:S,note:N.trim()||null})}).then(async H=>{const R=await H.json();if(!H.ok)throw new Error(R.message??"Failed");return R}),onSuccess:(g,S)=>{l({title:S.status==="resolved"?"Marked resolved":"Dismissed",description:`Review item ${S.id.slice(0,8)}⦠updated.`}),a.invalidateQueries({queryKey:["/api/admin-x9k2p7/reconciliation"]}),a.invalidateQueries({queryKey:["/api/admin-x9k2p7/reconciliation/health"]}),i(null),d("")},onError:g=>{l({title:"Error",description:g.message,variant:"destructive"})}}),n=((u=h.data)==null?void 0:u.openReviews.find(g=>g.id===m))??null,b=g=>g.includes("CONFLICT")||g.includes("AMBIGUOUS")?"bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300":g.includes("TEMPORAL")||g.includes("ORDER")?"bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300":"bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300",j=v.data,s=((D=h.data)==null?void 0:D.openReviews)??[];return e.jsxs("div",{className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Es,{className:"w-5 h-5 text-teal-500"}),e.jsx("span",{className:"font-semibold text-base",children:"Reconciliation Review Queue"}),e.jsxs(_,{variant:"ghost",size:"sm",className:"ml-auto",onClick:()=>{a.invalidateQueries({queryKey:["/api/admin-x9k2p7/reconciliation"]}),a.invalidateQueries({queryKey:["/api/admin-x9k2p7/reconciliation/health"]})},children:[e.jsx(he,{className:"w-3.5 h-3.5 mr-1"})," Refresh"]})]}
33),j&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[{label:"Open reviews",value:j.openReviews,accent:j.openReviews>0?"border-amber-400":"border-border"},{label:"Resolved",value:j.resolvedReviews,accent:"border-border"},{label:"Dismissed",value:j.dismissedReviews,accent:"border-border"},{label:"Total streams",value:j.totalStreams,accent:"border-border"},{label:"Failed runs",value:j.failedRuns,accent:j.failedRuns>0?"border-red-400":"border-border"}].map(({label:g,value:S,accent:N})=>e.jsxs("div",{className:`rounded-lg border-2 ${N} bg-card p-4`,children:[e.jsx("p",{className:"text-2xl font-bold tabular-nums",children:S??"â"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:g})]},g))}),v.isLoading&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:Array.from({length:5}).map((g,S)=>e.jsx(Y,{className:"h-20 rounded-lg"},S))}),h.isLoading&&e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((g,S)=>e.jsx(Y,{className:"h-20 rounded-lg"},S))}),h.isError&&e.jsx("div",{className:"rounded-lg border border-red-300 bg-red-50 dark:bg-red-950 p-4 text-sm text-red-700 dark:text-red-300",children:"Failed to load review items â check server logs."}),!h.isLoading&&s.length===0&&e.jsxs("div",{className:"rounded-lg border border-green-300 bg-green-50 dark:bg-green-950 p-6 flex items-center gap-3",children:[e.jsx(Z,{className:"w-5 h-5 text-green-600 shrink-0"}),e.jsx("p",{className:"text-sm text-green-800 dark:text-green-200",children:"No open reconciliation review items â all clear."})]}),s.length>0&&e.jsxs("div",{className:"rounded-lg border overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-2 bg-muted/40 text-xs font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-2",children:[e.jsx(ee,{className:"w-3.5 h-3.5 text-amber-500"}),s.length," open item",s.length!==1?"s":""," awaiting human confirmation"]}),e.jsxs(W,{children:[e.jsx(J,{children:e.jsxs(A,{children:[e.jsx(x,{className:"w-[180px]",children:"Reason code"}),e.jsx(x,{children:"Canonical event"}),e.jsx(x,{children:"Related event"}),e.jsx(x,{className:"w-[140px]",children:"Run ID"}),e.jsx(x,{className:"w-[140px]",children:"Created"}),e.jsx(x,{className:"w-[180px] text-right",children:"Actions"})]})}),e.jsx(V,{children:s.map(g=>e.jsxs(A,{children:[e.jsx(c,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-mono font-medium ${b(g.reasonCode)}`,children:g.reasonCode})}),e.jsxs(c,{className:"font-mono text-xs text-muted-foreground",children:[g.canonicalEventId.slice(0,8),"â¦"]}),e.jsx(c,{className:"font-mono text-xs text-muted-foreground",children:g.relatedEventId?`${g.relatedEventId.slice(0,8)}â¦`:e.jsx("span",{className:"text-muted-foreground/50",children:"â"})}),e.jsxs(c,{className:"font-mono text-xs text-muted-foreground truncate max-w-[120px]",children:[g.runId.slice(0,12),"â¦"]}),e.jsx(c,{className:"text-xs text-muted-foreground",children:new Date(g.createdAt).toLocaleString("en-GB",{dateStyle:"short",timeStyle:"short"})}),e.jsx(c,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs(_,{size:"sm",variant:"outline",className:"h-7 px-2 text-xs border-green-400 text-green-700 hover:bg-green-50 dark:hover:bg-green-950",onClick:()=>{i(g.id),o("resolved"),d("")},children:[e.jsx(Z,{className:"w-3.5 h-3.5 mr-1"})," Resolve"]}),e.jsxs(_,{size:"sm",variant:"outline",className:"h-7 px-2 text-xs border-gray-300 text-muted-foreground hover:bg-muted",onClick:()=>{i(g.id),o("dismissed"),d("")},children:[e.jsx(ve,{className:"w-3.5 h-3.5 mr-1"})," Dismiss"]})]})})]},g.id))})]})]}),s.length>0&&e.jsx("div",{className:"space-y-2",children:s.filter(g=>g.detail&&Object.keys(g.detail).length>0).map(g=>e.jsxs("details",{className:"rounded-lg border text-xs",children:[e.jsxs("summary",{className:"px-4 py-2 cursor-pointer text-muted-foreground hover:text-foreground select-none font-mono",children:[g.id.slice(0,8),"⦠· detail"]}),e.jsx("pre",{className:"px-4 pb-3 pt-1 text-xs font-mono whitespace-pre-wrap break-all bg-muted/30 rounded-b-lg",children:JSON.stringify(g.detail,null,2)})]},g.id))}),e.jsx(ks,{open:!!m,onOpenChange:g=>{g||(i(null),d(""))},children:e.jsxs(Cs,{className:"max-w-md",children:[e.jsxs(Ss,{children:[e.jsx(Rs,{className:"flex items-center gap-2",children:r==="resolved"?e.jsxs(e.Fragment,{children:[e.jsx(Z,{className:"w-4 h-4 text-green-600"})," Mark as Resolved"]}):e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"w-4 h-4 text-gray-500"})," Dismiss Review Item"]})}),e.jsx(As,{className:"text-xs font-mono mt-1",children:n==null?void 0:n.id})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[n&&e.jsxs("div",{className:"rounded-md bg-muted/40 p-3 space-y-1 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"Reason code: "}),e.jsx("span",{className:"font-mono",children:n.reasonCode})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"Canonical event: "}),e.jsxs("span",{className:"font-mono",children:[n.canonicalEventId.slice(0,8),"â¦"]})]}),n.relatedEventId&&e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"Related event: "}),e.jsxs("span",{className:"font-mono",children:[n.relatedEventId.slice(0,8),"â¦"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"Engine: "}),e.jsx("span",{className:"font-mono",children:n.engineVersion})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-sm font-medium",children:["Operational note ",e.jsx("span",{className:"text-muted-foreground font-normal",children:"(optional â no clinical prose)"})]}
33),e.jsx(ws,{placeholder:"e.g. Confirmed temporal order correct â upstream report timestamp corrected",value:f,onChange:g=>d(g.target.value),maxLength:500,rows:3,className:"text-sm"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[f.length,"/500"]})]})]}),e.jsxs(Ds,{children:[e.jsx(_,{variant:"outline",onClick:()=>{i(null),d("")},children:"Cancel"}),e.jsxs(_,{variant:r==="resolved"?"default":"secondary",disabled:k.isPending,onClick:()=>m&&k.mutate({id:m,status:r,note:f}),children:[k.isPending?e.jsx(Ne,{className:"w-4 h-4 mr-2 animate-spin"}):null,r==="resolved"?"Confirm Resolved":"Confirm Dismiss"]})]})]})})]})}function bt(){var oe,De,Ue,Qe,Ke,He,Ge,ze,We,Je,Ve,Ze,Ye,Xe,es,ss,ts,as,rs,ns,ls,is,ds,cs,os,xs,ms;const[,a]=Ls(),[l,m]=P.useState("audit"),[i,r]=P.useState(null),o=ae({mutationFn:()=>re("/api/admin-x9k2p7/backup/drill","POST").then(y=>y.json()),onSuccess:y=>r(y)}),f=U({queryKey:["/api/leads/auth/me"],queryFn:te({on401:"returnNull"}),retry:!1}),d=!f.isLoading&&!((oe=f.data)!=null&&oe.authenticated);P.useEffect(()=>{d&&a("/admin/leads/login")},[d,a]);const h=U({queryKey:["/api/admin-x9k2p7/audit/production-daily"],queryFn:te({on401:"returnNull"}),enabled:((De=f.data)==null?void 0:De.authenticated)===!0,refetchInterval:12e4}),v=U({queryKey:["/api/admin-x9k2p7/stripe/provisioning-incidents"],queryFn:te({on401:"returnNull"}),enabled:((Ue=f.data)==null?void 0:Ue.authenticated)===!0}),k=U({queryKey:["/api/admin-x9k2p7/audit/cron-heartbeats"],queryFn:te({on401:"returnNull"}),enabled:((Qe=f.data)==null?void 0:Qe.authenticated)===!0,refetchInterval:12e4}),n=U({queryKey:["/api/admin-x9k2p7/dob-repair-no-evidence"],queryFn:()=>fetch("/api/admin-x9k2p7/dob-repair-no-evidence",{credentials:"include"}).then(y=>y.json()),enabled:((Ke=f.data)==null?void 0:Ke.authenticated)===!0,staleTime:6e4,refetchInterval:12e4});if(f.isLoading)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx("div",{className:"w-6 h-6 border-2 border-t-transparent rounded-full animate-spin border-amber-600"})});if(d)return null;const b=((He=h.data)==null?void 0:He.latest)??null,j=((Ge=h.data)==null?void 0:Ge.history)??[],s=((ze=v.data)==null?void 0:ze.incidents)??[],u=s.filter(y=>y.status==="pending"||y.status==="monitoring").length,D=((We=b==null?void 0:b.summary)==null?void 0:We.activeSubscriptionsWithoutDbOwner)??0,g=((Je=b==null?void 0:b.summary)==null?void 0:Je.wouldCancel)??0,S=(Ve=b==null?void 0:b.summary)==null?void 0:Ve.latestBackupAgeHours,N=(Ze=b==null?void 0:b.checks)==null?void 0:Ze.find(y=>y.name==="webhook_health"),H=(Ye=N==null?void 0:N.meta)==null?void 0:Ye.latestWebhookAt,R=Date.now()-864e5,w=s.filter(y=>new Date(y.createdAt).getTime()>R).length,M=j.find(y=>y.overallStatus==="healthy"),p=(M==null?void 0:M.runAt)??null,G=s.filter(y=>y.status==="pending"||y.status==="monitoring"),O=G.length>0?Math.max(...G.map(y=>Date.now()-new Date(y.incidentDate).getTime())):null,z=O!==null?O/36e5:null;function Q(y){const de=Math.floor(y/36e5);return de<24?`${de}h`:`${Math.floor(de/24)}d ${de%24}h`}const le=((Xe=k.data)==null?void 0:Xe.latestByJob)??{},B=le.provisioning_gap_check??null,ie=le.production_audit??null,q=(ie==null?void 0:ie.ranAt)??(b==null?void 0:b.runAt)??null,pe=q?Date.now()-new Date(q).getTime():null,ce=pe!==null&&pe>24*36e5,t=B?Date.now()-new Date(B.ranAt).getTime():null,C=t!==null&&t>30*36e5,se=((es=n.data)==null?void 0:es.count)??((ts=(ss=n.data)==null?void 0:ss.rows)==null?void 0:ts.length)??0;return e.jsxs("div",{className:"min-h-screen bg-gray-50 dark:bg-gray-900",children:[e.jsxs("header",{className:"border-b bg-white dark:bg-gray-800 px-6 py-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($e,{className:"w-6 h-6 text-amber-600"}),e.jsx("h1",{className:"text-xl font-semibold",children:"Operations"}),b&&e.jsx(Le,{status:b.overallStatus})]}),e.jsx(Ks,{current:"ops"})]}),e.jsxs("div",{className:"max-w-6xl mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 ga
33p-3",children:[e.jsx(K,{icon:$e,label:"Last audit run",value:b?b.overallStatus.toUpperCase():"â",sub:q?ue(q):"No data",highlight:ce?"red":b?b.overallStatus==="healthy"?"green":b.overallStatus==="warning"?"amber":"red":void 0}),e.jsx(K,{icon:Re,label:"Audit cron alive",value:ce?"STALE":q?"OK":"NEVER",sub:q?`Ran ${ue(q)}`:"No heartbeat yet",highlight:ce?"red":q?"green":"amber"}),e.jsx(K,{icon:Ae,label:"Last healthy audit",value:p?ue(p):"â",sub:p?new Date(p).toLocaleDateString():"No healthy run yet",highlight:p?Date.now()-new Date(p).getTime()>48*36e5?"red":"green":"amber"}),e.jsx(K,{icon:Re,label:"Gap check",value:B?B.status==="error"?"ERROR":C?"STALE":"OK":"NEVER",sub:B?B.status==="error"?`Failed ${ue(B.ranAt)}`:`Ran ${ue(B.ranAt)}`:"No heartbeat yet",highlight:B?B.status==="error"||C?"red":"green":"amber"}),e.jsx(K,{icon:we,label:"Unresolved incidents",value:u,sub:w>0?`+${w} in last 24h`:"No new in 24h",highlight:u>0?"red":"green"}),e.jsx(K,{icon:ee,label:"New incidents (24h)",value:w,sub:w>0?"Alert sent to Stephen":"Clean",highlight:w>0?"red":"green"}),e.jsx(K,{icon:Ae,label:"Oldest unresolved",value:z!==null?Q(O):"â",sub:z!==null?z>72?"Critical â >72h":z>48?"Stale â >48h":"Open":"No open incidents",highlight:z===null?"green":z>72?"red":z>48?"amber":void 0}),e.jsx(K,{icon:Fs,label:"Orphan subscriptions",value:D,sub:"Active, no DB owner",highlight:D>0?"red":void 0}),e.jsx(K,{icon:Ie,label:"Would cancel",value:g,sub:"Dry-run count",highlight:g>0?"amber":void 0}),e.jsx(K,{icon:Me,label:"Last webhook",value:H?ue(H):"â",sub:(N==null?void 0:N.status)==="critical"?"CRITICAL â see audit":(N==null?void 0:N.status)==="warning"?"Warning â investigate":(N==null?void 0:N.status)==="healthy"?"Healthy":"checkout.session",highlight:(N==null?void 0:N.status)==="critical"?"red":(N==null?void 0:N.status)==="warning"?"amber":(N==null?void 0:N.status)==="healthy"&&H?"green":void 0}),e.jsx(K,{icon:Ws,label:"Backup age",value:S!=null?`${Math.round(S)}h`:"â",sub:S!=null?S>48?"STALE":"OK":"No data",highlight:S==null?void 0:S>48?"red":S>24?"amber":"green"})]}),N&&e.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg p-5 bg-white dark:bg-gray-900",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Re,{className:"w-4 h-4 text-gray-500"}),e.jsx("p",{className:"font-semibold text-sm text-gray-800 dark:text-gray-200",children:"Checkout Funnel â last 7 days"}),e.jsx("span",{className:"text-xs text-gray-400 ml-auto",children:"Stripe-confirmed data"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sessions opened"}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:((as=N.meta)==null?void 0:as.sessionsOpenedLast7d)??0})]}),e.jsxs("div",{className:"bg-green-50 dark:bg-green-950 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paid & provisioned"}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-green-700 dark:text-green-300",children:((rs=N.meta)==null?void 0:rs.newUsersLast7d)??0})]}),e.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Abandoned / expired"}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-gray-500",children:((ns=N.meta)==null?void 0:ns.sessionsAbandonedLast7d)??0}),e.jsx("p",{className:"text-xs text-gray-400 mt-0.5",children:"Not paid â no action"})]}),e.jsxs("div",{className:`rounded-lg p-3 ${(((ls=N.meta)==null?void 0:ls.potentiallyMissedWebhooks)??0)>0?"bg-red-50 dark:bg-red-950":"bg-gray-50 dark:bg-gray-800"}`,children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paid, not provisioned"}),e.jsx("p",{className:`text-2xl font-bold mt-1 ${(((is=N.meta)==null?void 0:is.potentiallyMissedWebhooks)??0)>0?"text-red-700 dark:text-red-300":""}`,children:((ds=N.meta)==null?void 0:ds.potentiallyMissedWebhooks)??0}),(((cs=N.meta)==null?void 0:cs.potentiallyMissedWebhooks)??0)>0&&e.jsx("p",{className:"text-xs text-red-600 dark:text-red-400 mt-0.5",children:"Use Recovery tab"})]})]}),(((os=N.meta)==null?void 0:os.pendingWebhookAlertCount)??0)>0&&e.jsxs("div",{className:"mt-4 p-3 rounded-lg bg-red-50 dark:bg-red-950 border border-red-300 dark:border-red-700",children:[e.jsxs("p",{className:"text-xs font-semibold text-red-700 dark:text-red-300",children:["â ",(xs=N.meta)==null?void 0:xs.pendingWebhookAlertCount," Stripe payment event(s) with pending delivery â Stripe cannot reach our endpoint"]}),e.jsxs("p",{className:"text-xs text-red-600 dark:text-red-400 mt-1",children:["Check the"," ",e.jsx("a",{href:"https://dashboard.stripe.com/webhooks",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"Stripe Webhooks Dashboard"})," ","â Recent Deliveries immediately. The event-replay at 05:00 Zurich will auto-recover, but manual review is needed now."]})]})]}),e.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg p-5 bg-white dark:bg-gray-900",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm text-gray-800 dark:text-gray-200",children:"Restore drill"}),e.jsx("p",{className:"text-xs text-gray-400 mt-0.5",children:"Downloads latest backup from S3, decrypts it, verifies SHA-256 and SQL structure. Read-only â does not touch the live database."})]}),e.jsx("button",{onClick:()=>o.mutate(),disabled:o.isPending,className:"px-4 py-2 text-xs font-semibold uppercase tracking-wide rounded bg-[#0E1A2B] text-white hover:bg-[#1a2e4a] disabled:opacity-50 disabled:cursor-not-allowed shrink-0 ml-4",children:o.isPending?"Runningâ¦":"Run drill"})]}),o.isError&&e.jsxs("p",{className:"text-xs text-red-600 dark:text-red-400 mt-2",children:["Drill failed: ",((ms=o.error)==null?void 0:ms.message)??"
33Unknown error"]}),i&&(()=>{const y=i,de=y.passed,xe=y.criticalTablesMissing??[],Ce=y.criticalTablesPresent??[],Te=y.warnings??[],Ee=y.errors??[];return e.jsxs("div",{className:`mt-3 rounded p-4 border text-xs font-mono space-y-2 ${de?"border-emerald-300 bg-emerald-50 dark:bg-emerald-950":"border-red-300 bg-red-50 dark:bg-red-950"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:`font-bold text-sm ${de?"text-emerald-700 dark:text-emerald-300":"text-red-700 dark:text-red-300"}`,children:de?"â
PASSED":"â FAILED"}),e.jsx("span",{className:"text-gray-500",children:y.timestamp})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-1 text-gray-700 dark:text-gray-300",children:[e.jsx("span",{children:"Backup key"}),e.jsx("span",{className:"truncate",children:y.backupKey}),e.jsx("span",{children:"Backup date"}),e.jsx("span",{children:y.backupTimestamp}),e.jsx("span",{children:"Size"}),e.jsxs("span",{children:[y.backupSizeMb," MB"]}),e.jsx("span",{children:"SHA-256"}),e.jsx("span",{className:y.sha256Match?"text-emerald-600":"text-red-600",children:y.sha256Match?"â match":"â mismatch"}),e.jsx("span",{children:"DB name"}),e.jsx("span",{children:y.dbName??"not found in header"}),e.jsx("span",{children:"Tables found"}),e.jsx("span",{children:y.tableCount}),e.jsx("span",{children:"COPY blocks"}),e.jsx("span",{children:y.copyBlockCount})]}),Ce.length>0&&e.jsxs("div",{className:"mt-1",children:[e.jsx("span",{className:"text-emerald-700 dark:text-emerald-400 font-semibold",children:"Critical tables â "}),e.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:Ce.join(", ")})]}),xe.length>0&&e.jsxs("div",{className:"mt-1",children:[e.jsx("span",{className:"text-amber-700 dark:text-amber-400 font-semibold",children:"Not in sample: "}),e.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:xe.join(", ")})]}),Te.map((X,ne)=>e.jsxs("p",{className:"text-amber-700 dark:text-amber-400",children:["â ",X]},ne)),Ee.map((X,ne)=>e.jsxs("p",{className:"text-red-700 dark:text-red-400",children:["â ",X]},ne)),y.sqlHeader&&e.jsxs("p",{className:"text-gray-500 truncate",children:["Header: ",y.sqlHeader]})]})})()]}),(()=>{var Ce,Te,Ee;const y=(Ce=b==null?void 0:b.checks)==null?void 0:Ce.find(X=>X.name==="cancel_safety"),de=(y==null?void 0:y.status)==="critical",xe=(Te=y==null?void 0:y.meta)==null?void 0:Te.criticalOrphans;if(de&&((xe==null?void 0:xe.length)??0)>0)return e.jsxs("div",{className:"border-2 border-red-500 bg-red-50 dark:bg-red-950 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(ve,{className:"w-6 h-6 text-red-600 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-red-700 dark:text-red-300 text-sm",children:"CRITICAL â Orphan subscription(s) detected"}),e.jsxs("p",{className:"text-sm text-red-600 dark:text-red-400 mt-1",children:[xe.length," active Stripe subscription",xe.length>1?"s":""," found with no DB owner and no confirmed-internal email. These cannot be automatically cancelled â manual review is required immediately."]}),e.jsx("ul",{className:"mt-2 space-y-0.5",children:xe.map((X,ne)=>e.jsxs("li",{className:"text-xs font-mono text-red-700 dark:text-red-300",children:[X.subId,X.email?` â ${X.email}`:" â no email"]},ne))})]})]});if(g>0){const X=(Ee=y==null?void 0:y.meta)==null?void 0:Ee.candidates;return e.jsxs("div",{className:"border border-amber-300 bg-amber-50 dark:bg-amber-950 rounded-lg p-4 flex items-start gap-3",children:[e.jsx(ee,{className:"w-5 h-5 text-amber-600 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-amber-800 dark:text-amber-300 text-sm",children:["Internal/test subscription",g>1?"s":""," detected â no customer risk"]}),e.jsxs("p",{className:"text-sm text-amber-700 dark:text-amber-400 mt-1",children:["The dry-run found ",e.jsx("strong",{children:g})," subscription",g>1?"s":""," belonging to internal/test accounts. No live cancellation has been performed. These are safe to cancel manually when ready â expand the ",e.jsx("span",{className:"font-mono",children:"cancel_safety"})," check in the Daily Audit tab for details."]}),X&&X.length>0&&e.jsx("ul",{className:"mt-2 space-y-0.5",children:X.map((ne,Ms)=>e.jsxs("li",{className:"text-xs font-mono text-amber-800 dark:text-amber-200",children:[ne.subscriptionId,ne.customerEmail?` â ${ne.customerEmail}`:"",ne.plan?` (${ne.plan})`:""]},Ms))})]})]})}return null})(),e.jsxs("div",{className:"flex gap-1 border-b",children:[e.jsx("button",{type:"button",onClick:()=>m("audit"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="audit"?"border-amber-500 text-amber-700 dark:text-amber-400":"border-transparent text-muted-foreground hover:text-foreground"}`,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(he,{className:"w-4 h-4"})," Daily Audit"]})}),e.jsx("button",{type:"button",onClick:()=>m("incidents"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="incidents"?"border-amber-500 text-amber-700 dark:text-amber-400":"border-transparent text-muted-foreground hover:text-foreground"}`,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(we,{className:"w-4 h-4"})," Provisioning Incidents",u>0&&e.jsx("span",{className:"bg-red-500 text-white text-xs rounded-full px-1.5 py-0.5 leading-none",children:u})]})}),e.jsx("button",{type:"button",onClick:()=>m("recovery"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="recovery"?"border-amber-500 text-amber-700 dark:text-amber-400":"border-transparent text-muted-foreground hover:text-foreground"}`,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Me,{className:"w-4 h-4"})," Recovery Tools"]})}),e.jsx("button",{type:"button",onClick:()=>m("lab"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="lab"?"border-amber-500 text-amber-700 dark:text-amber-400":"border-transparent text-muted-foreground hover:text-foreground"}`,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(_e,{className:"w-4 h-4"}
33)," Lab Extraction"]})}),e.jsx("button",{type:"button",onClick:()=>m("backups"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="backups"?"border-amber-500 text-amber-700 dark:text-amber-400":"border-transparent text-muted-foreground hover:text-foreground"}`,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"w-4 h-4"})," Backups"]})}),e.jsx("button",{type:"button",onClick:()=>m("bots"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="bots"?"border-amber-500 text-amber-700 dark:text-amber-400":"border-transparent text-muted-foreground hover:text-foreground"}`,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Is,{className:"w-4 h-4"})," Bot Crawl"]})}),e.jsx("button",{type:"button",onClick:()=>m("ai"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="ai"?"border-violet-500 text-violet-700 dark:text-violet-400":"border-transparent text-muted-foreground hover:text-foreground"}`,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ts,{className:"w-4 h-4"})," AI Usage"]})}),e.jsx("button",{type:"button",onClick:()=>m("funnel"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="funnel"?"border-amber-500 text-amber-700 dark:text-amber-400":"border-transparent text-muted-foreground hover:text-foreground"}`,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-4 h-4"})," Retail Funnel"]})}),e.jsx("button",{type:"button",onClick:()=>m("recon-review"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="recon-review"?"border-teal-500 text-teal-700 dark:text-teal-400":"border-transparent text-muted-foreground hover:text-foreground"}`,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Es,{className:"w-4 h-4"})," Recon Review"]})}),e.jsx("button",{type:"button",onClick:()=>m("dob-repair"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="dob-repair"?"border-orange-500 text-orange-700 dark:text-orange-400":"border-transparent text-muted-foreground hover:text-foreground"}`,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Oe,{className:"w-4 h-4"})," DOB Repair",se>0&&e.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold bg-orange-500 text-white",children:se})]})})]}),l==="audit"&&e.jsx(et,{}),l==="incidents"&&e.jsx(st,{}),l==="recovery"&&e.jsx(tt,{webhookStatus:N==null?void 0:N.status}),l==="lab"&&e.jsx(nt,{}),l==="backups"&&e.jsx(ht,{}),l==="bots"&&e.jsx(ut,{}),l==="ai"&&e.jsx(xt,{}),l==="funnel"&&e.jsx(pt,{}),l==="recon-review"&&e.jsx(jt,{}),l==="dob-repair"&&e.jsx(gt,{})]})]})}function Bt(){return e.jsx(Zs,{children:e.jsx(bt,{})})}
33export{Bt 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.