1import{c as ue,M as Z,s as u,Z as C,g as m,r as _,j as e,N as me,_ as Ie,B as p,U as V,O as xe,Q as he,V as pe,Y as fe,I as K,J as g,bq as Te,h as B,i as z,k as H,m as G,a4 as $e,K as Le,e as De}from"./index-DLd_kDlx.js";import{S as Fe,a as Ae}from"./SuperAdminLayout-BsUvQU2j.js";import{T as Be,a as Ge,b as te,c as re}from"./tabs-DKw2ItQa.js";import{S as ne,a as ae,b as ie,c as le,d as A}from"./select-RSrodAEw.js";import{T as ge,a as je,b as F,c as D,d as ye,e as k}from"./table-BOJIo-OD.js";import{u as E}from"./useMutation-CotV56Sa.js";import{L as O}from"./label-D4-ENrYn.js";import{S as ce}from"./switch-7Twrb7Os.js";import{L as oe}from"./loader-circle-D2miE2xB.js";import{P as de}from"./play-rljZUdXx.js";import{L as W}from"./link-_ZZxygmy.js";import{T as Oe}from"./triangle-alert-Chqk_WK7.js";import{Z as X}from"./zap-Cs6U3-LC.js";import{R as ve}from"./rotate-ccw-Bx1C64Ur.js";import{R as _e}from"./refresh-cw-CoPjtj5-.js";import{T as Ke}from"./trash-2-0uuZSTFd.js";import{S as Qe}from"./search-DFH5eAlA.js";import{G as Ue}from"./gauge-BaUzh1VV.js";import"./NotificationIcon-C1wwYnH5.js";import"./popover-BMD5FOmU.js";import"./scroll-area-BXTuUF24.js";import"./index-Deh-4PO1.js";import"./index-BdQq_4o_.js";import"./NotificationItem-Dc2WXW-y.js";import"./formatDistanceToNow-57P64IbE.js";import"./en-US-9SRVm7yB.js";import"./differenceInCalendarMonths-BA0TPVs2.js";import"./endOfDay-DkR3ZXc8.js";import"./endOfMonth-CYn6pTOm.js";import"./message-square-CtxeCfRz.js";import"./trophy-DBX-jNOC.js";import"./dropdown-menu-DSd1c3Vk.js";import"./index-lTaZyIGy.js";import"./chevron-right-CD1gvy-q.js";import"./crown-hzm_bRIt.js";import"./user-check-DxoAQXwU.js";import"./star-BH1OFEcs.js";import"./globe-C057RQ73.js";import"./timer-CZhDpZys.js";import"./briefcase-business-CphIeAJd.js";import"./key-round-B79BulHq.js";import"./chevron-down-DpJJsCer.js";import"./chevron-up-M4SAwIjf.js";/** 2 * @license lucide-react v0.462.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 Ne=ue("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/** 7 * @license lucide-react v0.462.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 Me=ue("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]]);function ze(){var i,c;const r=Z({queryKey:["dareyscore-diag","pipeline-health"],queryFn:async()=>{const{data:n,error:h}=await u.rpc("admin_dareyscore_diagnostics");if(h)throw h;return n},refetchInterval:12e4,refetchIntervalInBackground:!1,staleTime:6e4}),s={...r,data:r.data?{withGuid:r.data.guid_resolution.with_guid,total:r.data.guid_resolution.total,withoutGuid:r.data.guid_resolution.without_guid}:void 0},t={...r,data:(i=r.data)==null?void 0:i.pending_events},a={...r,data:r.data?{failed:r.data.failed_events,auditOnly:r.data.audit_only_events}:void 0},l={...r,data:((c=r.data)==null?void 0:c.last_sync)??null};return{guidResolution:s,pendingEvents:t,failedEvents:a,lastSync:l}}function He(r){return Z({queryKey:["dareyscore-diag","learner-lookup",r],queryFn:async()=>{var x,L,f;if(!r)return null;const{data:s}=await u.from("xterns_profiles").select("user_id, full_name, email").ilike("email",`%${r}%`).limit(1);let t=null,a=null,l=null;const i=s==null?void 0:s[0];if(i)t=i.user_id,a=i.full_name||null,l=i.email||null;else try{const N=new URLSearchParams({action:"list-users",search:r,page:"1",limit:"10",role:"all",sort_created:"desc"}),{data:b}=await u.functions.invoke(`superadmin-users?${N.toString()}`,{method:"GET"}),Q=r.toLowerCase(),S=((b==null?void 0:b.users)??[]).find(U=>(U.email??"").toLowerCase()===Q)??((b==null?void 0:b.users)??[])[0];S&&(t=S.id,a=S.full_name||null,l=S.email||null)}catch{}if(!t)return null;const[c,n,h,T]=await Promise.all([u.from("ei_scores").select("*").eq("user_id",t).order("calculated_at",{ascending:!1}).limit(1),u.from("dareyscore_identity_mappings").select("*").eq("user_id",t).limit(1),u.from("dareyscore_event_queue").select("id, sent_at, last_error").eq("user_id",t),u.from("profiles").select("full_name").eq("id",t).maybeSingle()]),j=((x=c.data)==null?void 0:x[0])??null,P=((L=n.data)==null?void 0:L[0])??null,R=h.data??[],v=R.filter(N=>!N.sent_at).length,$=R.filter(N=>N.last_error&&N.last_error!=="audit_only_not_sent"&&N.last_error.toLowerCase().includes("error")).length;
11return{userId:t,fullName:a||((f=T.data)==null?void 0:f.full_name)||"â",email:l||r,guid:(P==null?void 0:P.dareyscore_guid)??null,localScore:(j==null?void 0:j.score)??null,scoreBreakdown:(j==null?void 0:j.score_breakdown)??null,calculatedAt:(j==null?void 0:j.calculated_at)??null,totalEvents:R.length,pendingEvents:v,failedEvents:$}},enabled:!!r})}function Ve(r){return Z({queryKey:["dareyscore-diag","event-queue",r],queryFn:async()=>{let t=u.from("dareyscore_event_queue").select("*",{count:"exact"}).order("created_at",{ascending:!1}).range(r.page*20,(r.page+1)*20-1);r.status==="pending"?t=t.is("sent_at",null):r.status==="sent"?t=t.not("sent_at","is",null).or("last_error.is.null,last_error.eq.audit_only_not_sent"):r.status==="failed"?t=t.not("last_error","is",null).neq("last_error","audit_only_not_sent"):r.status==="audit_only"&&(t=t.eq("last_error","audit_only_not_sent")),r.eventType&&(t=t.eq("event_type",r.eventType)),r.userSearch&&(t=t.ilike("user_id",`%${r.userSearch}%`));const{data:a,count:l}=await t,i=[...new Set((a??[]).map(n=>n.user_id))];let c={};if(i.length>0){const{data:n}=await u.from("xterns_profiles").select("user_id, email").in("user_id",i);c=Object.fromEntries((n??[]).map(h=>[h.user_id,h.email]))}return{events:(a??[]).map(n=>({...n,userEmail:c[n.user_id]??n.user_id})),totalCount:l??0,pageSize:20}}})}function Ze(){return Z({queryKey:["dareyscore-diag","event-types"],queryFn:async()=>{const{data:r}=await u.from("dareyscore_event_queue").select("event_type");return[...new Set((r??[]).map(t=>t.event_type))].sort()},staleTime:6e4})}function Ye(r){return Z({queryKey:["dareyscore-diag","learners-without-guid"],queryFn:async()=>{const{data:s}=await u.from("dareyscore_identity_mappings").select("user_id"),t=new Set((s??[]).map(i=>i.user_id)),{data:a}=await u.from("xterns_profiles").select("user_id, full_name, email");return(a??[]).filter(i=>!t.has(i.user_id)).map(i=>({userId:i.user_id,fullName:i.full_name,email:i.email}))},enabled:r})}const w="dareyscore-diag";function Je(){const r=C();return E({mutationFn:async()=>{const{data:s,error:t}=await u.functions.invoke("send-dareyscore-batch",{body:{immediate:!0}});if(t)throw t;return s},onSuccess:s=>{m.success(`Batch sync triggered: ${(s==null?void 0:s.events_sent)??0} events sent, ${(s==null?void 0:s.users_processed)??0} users processed`),r.invalidateQueries({queryKey:[w]})},onError:s=>m.error(`Batch sync failed: ${s.message}`)})}function be(){const r=C();return E({mutationFn:async(s={})=>{const{data:t,error:a}=await u.functions.invoke("backfill-dareyscore-profile-snapshots",{body:{limit:500,max_batches:10,...s}});if(a)throw a;if(t!=null&&t.error)throw new Error(t.error);return t},onSuccess:s=>{m.success(`Profile snapshot backfill complete: ${(s==null?void 0:s.events_sent)??0} events sent, ${(s==null?void 0:s.profiles_scanned)??0} profiles scanned`),r.invalidateQueries({queryKey:[w]}),r.invalidateQueries({queryKey:[w,"learner-lookup"]}),r.invalidateQueries({queryKey:["talent-pipeline"]})},onError:s=>m.error(`Profile snapshot backfill failed: ${s.message}`)})}function we(){const r=C();return E({mutationFn:async s=>{const{data:t,error:a}=await u.functions.invoke("send-dareyscore-batch",{body:{immediate:!0,target_user_id:s}});if(a)throw a;return t},onSuccess:s=>{m.success(`User sync triggered: ${(s==null?void 0:s.events_sent)??0} events sent`),r.invalidateQueries({queryKey:[w]})},onError:s=>m.error(`User sync failed: ${s.message}`)})}function Se(){const r=C();return E({mutationFn:async s=>{const{data:t,error:a}=await u.functions.invoke("link-dareyscore-identity",{body:{user_id:s,force_refresh:!0}});if(a)throw a;return t},onSuccess:()=>{m.success("GUID resolution triggered"),r.invalidateQueries({queryKey:[w]}),r.invalidateQueries({queryKey:[w,"learner-lookup"]})},onError:s=>m.error(`GUID resolution failed: ${s.message}`)})}function We(){const r=C();return E({mutationFn:async s=>{const{data:t,error:a}=await u.rpc("calculate_basic_ei_score",{p_user_id:s});if(a)throw a;return t},onSuccess:()=>{m.success("Score recalculated"),r.invalidateQueries({queryKey:[w]})},onError:s=>m.error(`Recalculation failed: ${s.message}`)})}function Xe(){const r=C();return E({mutationFn:async s=>{const{data:t,error:a}=await u.functions.invoke("fetch-dareyscore-score",{body:{user_id:s}});if(a)throw a;return t},onSuccess:s=>{var i,c;const t=((c=(i=s==null?void 0:s.score_breakdown)==null?void 0:i.details)==null?void 0:c.peak_score)??0,a=(s==null?void 0:s.score)??0;((s==null?void 0:s.status)??"ready")==="processing"?m.info("Signal Score is still processing â check back shortly"):m.success(`Score refreshed: ${a} (peak ${t})`),r.invalidateQueries({queryKey:[w]}),r.invalidateQueries({queryKey:["ei-score"]})},onError:s=>m.error(`Refresh failed: ${s.message}`)})}function ke(){const r=C();return E({mutationFn:async s=>{let t=u.from("dareyscore_event_queue").select("id, last_error").not("last_error","is",null).neq("last_error","audit_only_not_sent");s&&(t=t.eq("user_id",s));const{data:a}=await t;if(!(a!=null&&a.length))return 0;const l=a.map(c=>c.id),{error:i}=await u.from("dareyscore_event_queue").update({sent_at:null,retry_count:0,last_error:null}).in("id",l);if(i)throw i;return l.length},onSuccess:s=>{m.success(`${s} failed events reset for retry`),r.invalidateQueries({queryKey:[w]})},onError:s=>m.error(`Retry failed: ${s.message}`)})}function es(){const r=C();return E({mutationFn:async()=>{const{data:s}=await u.from("dareyscore_event_queue").select("id").is("sent_at",null).gte("retry_count",3);if(!(s!=null&&s.length))return 0;const t=s.map(l=>l.id),{error:a}=await u.from("dareyscore_event_queue").update({last_error:"permanently_failed",sent_at:new Date().toISOString()}).in("id",t);if(a)throw a;return t.length},onSuccess:s=>{m.success(`${s} stale events purged`),r.invalidateQueries({queryKey:[w]})},onError:s=>m.error(`Purge failed: ${s.message}`)})}function ss(){const r=C();return E({mutationFn:async()=>{const{data:s,error:t}=await u.from("ei_scores").select("user_id, score, calculated_at").order("calculated_at",{ascending:!1});if(t)throw t;if(!(s!=null&&s.length))return{recalculated:0,errors:0};const a=new Map;
11for(const n of s)a.has(n.user_id)||a.set(n.user_id,n.score);const l=[...a.entries()].filter(([,n])=>n===0).map(([n])=>n);if(!l.length)return{recalculated:0,errors:0};let i=0,c=0;for(let n=0;n<l.length;n+=5){const h=l.slice(n,n+5),T=await Promise.allSettled(h.map(j=>u.functions.invoke("calculate-ei-score",{body:{user_id:j}})));for(const j of T)j.status==="fulfilled"&&!j.value.error?i++:c++}return{recalculated:i,errors:c}},onSuccess:({recalculated:s,errors:t})=>{m.success(`Recalculated ${s} stale scores${t?`, ${t} errors`:""}`),r.invalidateQueries({queryKey:[w]}),r.invalidateQueries({queryKey:["talent-pipeline"]})},onError:s=>m.error(`Recalculation failed: ${s.message}`)})}function ts(){const r=C();return E({mutationFn:async()=>{const s=new Date(Date.now()-72e5).toISOString(),{data:t}=await u.from("dareyscore_event_queue").select("id").is("sent_at",null).is("last_error",null).lt("created_at",s);if(!(t!=null&&t.length))return 0;const a=t.map(i=>i.id),{error:l}=await u.from("dareyscore_event_queue").update({retry_count:0,last_error:"stuck_reset_for_retry"}).in("id",a);if(l)throw l;return await u.functions.invoke("send-dareyscore-batch",{body:{immediate:!0}}),a.length},onSuccess:s=>{m.success(`${s} stuck events flushed for retry`),r.invalidateQueries({queryKey:[w]})},onError:s=>m.error(`Flush failed: ${s.message}`)})}function rs(){const r=C();return E({mutationFn:async s=>{const{data:t,error:a}=await u.functions.invoke("send-dareyscore-batch",{body:{immediate:!0,target_user_ids:s}});if(a)throw a;return t},onSuccess:s=>{m.success(`Batch sync for ${(s==null?void 0:s.users_processed)??0} users triggered`),r.invalidateQueries({queryKey:[w]})},onError:s=>m.error(`Batch sync failed: ${s.message}`)})}const Y=()=>({batches:0,profiles:0,prepared:0,sent:0,accepted:0,rejected:0,byType:{},skippedReasons:{}}),ns=()=>{const r=C(),[s,t]=_.useState(!1),[a,l]=_.useState(!0),[i,c]=_.useState(!0),[n,h]=_.useState(100),[T,j]=_.useState(10),[P,R]=_.useState(0),[v,$]=_.useState(!1),[x,L]=_.useState(!1),[f,N]=_.useState(Y()),[b,Q]=_.useState(null),[S,U]=_.useState(null),M=_.useRef(!1),Ce=()=>{N(Y()),Q(null),U(null)},ee=async o=>{const{data:d,error:q}=await u.functions.invoke("backfill-dareyscore-profile-snapshots",{body:{limit:n,offset:o,max_batches:T,include_events:i,dry_run:a}});if(q)throw q;if(d!=null&&d.error)throw new Error(d.error);return d},se=(o,d)=>{const q={...o.byType};for(const[I,Re]of Object.entries(d.events_prepared_by_type??{}))q[I]=(q[I]??0)+Re;const y={...o.skippedReasons};for(const I of d.skipped??[])y[I.reason]=(y[I.reason]??0)+1;return{batches:o.batches+1,profiles:o.profiles+(d.profiles_scanned??0),prepared:o.prepared+(d.events_prepared??0),sent:o.sent+(d.events_sent??0),accepted:o.accepted+(d.accepted??0),rejected:o.rejected+(d.rejected??0),byType:q,skippedReasons:y}},qe=async()=>{$(!0);try{const o=S==null&&f.batches>0,d=o?Y():f;o&&(N(d),m.message("Cohort was complete â totals reset for new run from offset 0."));const y=await ee(S??P);Q(y),N(se(d,y)),U(y.next_offset),m.success(`Batch done · profiles=${y.profiles_scanned} prepared=${y.events_prepared} sent=${y.events_sent} accepted=${y.accepted??0} rejected=${y.rejected??0} next_offset=${y.next_offset??"â"}`),r.invalidateQueries({queryKey:["dareyscore-diag"]})}catch(o){m.error(`Backfill failed: ${o.message}`)}finally{$(!1)}},Ee=async()=>{$(!0),L(!0),M.current=!1;const o=S==null&&f.batches>0;let d=o?Y():f;o&&(N(d),m.message("Cohort was complete â totals reset for new sweep from offset 0."));let q=S??P;try{for(let y=0;y<200&&!M.current;y++){const I=await ee(q??0);if(Q(I),d=se(d,I),N(d),U(I.next_offset),q=I.next_offset,q==null)break}m.success(`Cohort backfill ${M.current?"stopped":"complete"} · profiles=${d.profiles} prepared=${d.prepared} sent=${d.sent} accepted=${d.accepted} rejected=${d.rejected}`),r.invalidateQueries({queryKey:["dareyscore-diag"]}),r.invalidateQueries({queryKey:["talent-pipeline"]})}catch(y){m.error(`Auto-loop failed: ${y.message}`)}finally{$(!1),L(!1)}},Pe=()=>{M.current=!0};return e.jsxs(me,{open:s,onOpenChange:o=>{t(o),o||(M.current=!0)},children:[e.jsx(Ie,{asChild:!0,children:e.jsxs(p,{variant:"outline",className:"gap-2",children:[e.jsx(V,{className:"h-4 w-4"}),"Cohort Backfillâ¦"]})}),e.jsxs(xe,{className:"max-w-2xl",children:[e.jsxs(he,{children:[e.jsx(pe,{children:"Cohort Backfill (Profile Snapshots + Historical Events)"}),e.jsxs(fe,{children:["Sweep all xterns profiles through ",e.jsx("code",{children:"backfill-dareyscore-profile-snapsh
11ots"}),". Always dry-run first to see the event volume before running live."]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between rounded border p-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"font-medium",children:"Dry run"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Prepare events but don't send"})]}),e.jsx(ce,{checked:a,onCheckedChange:l,disabled:v})]}),e.jsxs("div",{className:"flex items-center justify-between rounded border p-3",children:[e.jsxs("div",{children:[e.jsx(O,{className:"font-medium",children:"Include historical events"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"story_completed, pod_completed, etc."})]}),e.jsx(ce,{checked:i,onCheckedChange:c,disabled:v})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Limit (profiles per batch)"}),e.jsx(K,{type:"number",min:1,max:500,value:n,onChange:o=>h(Number(o.target.value)||1),disabled:v})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Max batches per invocation"}),e.jsx(K,{type:"number",min:1,max:50,value:T,onChange:o=>j(Number(o.target.value)||1),disabled:v})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Starting offset"}),e.jsx(K,{type:"number",min:0,value:P,onChange:o=>R(Number(o.target.value)||0),disabled:v})]}),e.jsxs("div",{children:[e.jsx(O,{className:"text-xs",children:"Next offset (resume from)"}),e.jsx(K,{value:S==null?"â":String(S),readOnly:!0})]})]}),e.jsxs("div",{className:"rounded border p-3 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[e.jsx(g,{variant:a?"secondary":"destructive",children:a?"DRY RUN":"LIVE"}),e.jsxs(g,{variant:"outline",children:["batches: ",f.batches]}),e.jsxs(g,{variant:"outline",children:["profiles: ",f.profiles]}),e.jsxs(g,{variant:"outline",children:["prepared: ",f.prepared]}),e.jsxs(g,{variant:"outline",children:["sent: ",f.sent]}),e.jsxs(g,{variant:"outline",children:["accepted: ",f.accepted]}),e.jsxs(g,{variant:f.rejected>0?"destructive":"outline",children:["rejected: ",f.rejected]}),Object.entries(f.skippedReasons).map(([o,d])=>e.jsxs(g,{variant:"destructive",children:[o,": ",d]},o)),S==null&&f.batches>0&&e.jsx(g,{className:"bg-green-600",children:"cohort complete"})]}),Object.keys(f.byType).length>0&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"By type:"})," ",Object.entries(f.byType).map(([o,d])=>`${o}=${d}`).join(", ")]}),b&&e.jsxs("div",{className:"rounded border border-dashed p-2 text-xs space-y-1",children:[e.jsx("div",{className:"font-medium text-foreground",children:"Last invocation (matches Signal Score API log):"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(g,{variant:"outline",children:["profiles: ",b.profiles_scanned]}),e.jsxs(g,{variant:"outline",children:["prepared: ",b.events_prepared]}),e.jsxs(g,{variant:"outline",children:["sent: ",b.events_sent]}),e.jsxs(g,{variant:"outline",children:["accepted: ",b.accepted??0]}),e.jsxs(g,{variant:(b.rejected??0)>0?"destructive":"outline",children:["rejected: ",b.rejected??0]}),e.jsxs(g,{variant:"outline",children:["next_offset: ",b.next_offset??"â"]})]}),e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer text-muted-foreground",children:"Full JSON"}),e.jsx("pre",{className:"mt-2 max-h-40 overflow-auto rounded bg-muted p-2",children:JSON.stringify(b,null,2)})]})]})]}),e.jsxs(Te,{className:"flex-wrap gap-2 sm:justify-between",children:[e.jsx(p,{variant:"ghost",onClick:Ce,disabled:v,children:"Reset totals"}),e.jsx("div",{className:"flex gap-2",children:v&&x?e.jsxs(p,{variant:"destructive",onClick:Pe,className:"gap-2",children:[e.jsx(Me,{className:"h-4 w-4"})," Stop after current"]}):e.jsxs(e.Fragment,{children:[e.jsxs(p,{variant:"outline",onClick:qe,disabled:v,className:"gap-2",children:[v?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(de,{className:"h-4 w-4"}),"Run one batch"]}),e.jsxs(p,{onClick:Ee,disabled:v,className:"gap-2",children:[v?e.jsx(oe,{className:"h-4 w-4 animate-spin"}):e.jsx(de,{className:"h-4 w-4"}),a?"Auto-loop (dry run)":"Auto-loop (LIVE)"]})]})})]})]})]})},as=(r,s=8)=>r?r.length>s?r.slice(0,s)+"â¦":r:null,J=r=>
11r?new Date(r).toLocaleString():"â",st=()=>{const[r,s]=_.useState(!1);return e.jsx(Fe,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ae,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Signal Score Diagnostics"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Monitor and troubleshoot the Signal Score sync pipeline"})]})]}),e.jsx(is,{onGuidClick:()=>s(!0)}),e.jsx(ls,{}),e.jsx(cs,{}),e.jsx(us,{open:r,onOpenChange:s})]})})},is=({onGuidClick:r})=>{const{guidResolution:s,pendingEvents:t,failedEvents:a,lastSync:l}=ze(),i=s.data,c=t.data??0,n=a.data,h=l.data;return e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs(B,{className:"cursor-pointer hover:ring-2 hover:ring-primary/30 transition-all",onClick:r,children:[e.jsx(z,{className:"pb-2",children:e.jsxs(H,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(W,{className:"h-4 w-4"})," GUID Resolution"]})}),e.jsxs(G,{children:[e.jsxs("p",{className:`text-2xl font-bold ${((i==null?void 0:i.withGuid)??0)>0?"text-green-600":"text-destructive"}`,children:[(i==null?void 0:i.withGuid)??0," / ",(i==null?void 0:i.total)??0]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(i==null?void 0:i.withoutGuid)??0," without GUID â click to view"]})]})]}),e.jsxs(B,{children:[e.jsx(z,{className:"pb-2",children:e.jsxs(H,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx($e,{className:"h-4 w-4"})," Events Pending"]})}),e.jsxs(G,{children:[e.jsx("p",{className:`text-2xl font-bold ${c>0?"text-amber-600":"text-green-600"}`,children:c}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Awaiting send"})]})]}),e.jsxs(B,{children:[e.jsx(z,{className:"pb-2",children:e.jsxs(H,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Oe,{className:"h-4 w-4"})," Events Failed"]})}),e.jsxs(G,{children:[e.jsx("p",{className:`text-2xl font-bold ${((n==null?void 0:n.failed)??0)>0?"text-destructive":"text-green-600"}`,children:(n==null?void 0:n.failed)??0}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(n==null?void 0:n.auditOnly)??0," audit-only"]})]})]}),e.jsxs(B,{children:[e.jsx(z,{className:"pb-2",children:e.jsxs(H,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Le,{className:"h-4 w-4"})," Last Sync"]})}),e.jsxs(G,{children:[e.jsx("p",{className:`text-lg font-bold ${h?"text-green-600":"text-destructive"}`,children:h?J(h):"Never"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Most recent score calculation"})]})]})]})},ls=()=>{const r=Je(),s=ke(),t=es(),a=ss(),l=ts(),i=be();return e.jsxs(B,{children:[e.jsx(z,{className:"pb-3",children:e.jsx(H,{className:"text-base",children:"Quick Actions"})}),e.jsxs(G,{className:"flex flex-wrap gap-3",children:[e.jsxs(p,{onClick:()=>r.mutate(),disabled:r.isPending,className:"gap-2",children:[e.jsx(X,{className:"h-4 w-4"}),r.isPending?"Syncingâ¦":"Trigger Batch Sync"]}),e.jsxs(p,{variant:"outline",onClick:()=>i.mutate({limit:500,max_batches:10}),disabled:i.isPending,className:"gap-2",children:[e.jsx(V,{className:"h-4 w-4"}),i.isPending?"Backfilling...":"Backfill Profile Snapshots"]}),e.jsx(ns,{}),e.jsxs(p,{variant:"outline",onClick:()=>s.mutate(void 0),disabled:s.isPending,className:"gap-2",children:[e.jsx(ve,{className:"h-4 w-4"}),s.isPending?"Retryingâ¦":"Retry Failed Events"]}),e.jsxs(p,{variant:"outline",onClick:()=>a.mutate(),disabled:a.isPending,className:"gap-2",children:[e.jsx(Ne,{className:"h-4 w-4"}),a.isPending?"Recalculatingâ¦":"Recalculate Stale Scores"]}),e.jsxs(p,{variant:"outline",onClick:()=>l.mutate(),disabled:l.isPending,className:"gap-2",children:[e.jsx(_e,{className:"h-4 w-4"}),l.isPending?"Flushingâ¦":"Flush Stuck Events"]}),e.jsxs(p,{variant:"outline",onClick:()=>t.mutate(),disabled:t.isPending,className:"gap-2 text-destructive border-destructive/30 hover:bg-destructive/10",children:[e.jsx(Ke,{className:"h-4 w-4"}),t.isPending?"Purgingâ¦":"Purge Stale Events"]})]})]})},cs=()=>e.jsxs(Be,{defaultValue:"learner-lookup",children:[e.jsxs(Ge,{children:[e.jsx(te,{value:"learner-lookup",children:"Learner Lookup"}),e.jsx(te,{value:"event-queue",children:"Event Queue"})]}),e.jsx(re,{value:"learner-lookup",children:e.jsx(os,{})}),e.jsx(re,{value:"event-queue",children:e.jsx(ds,{})})]}),os=()=>{const[r,s]=_.useState(""),[t,a]=_.useState(""),{data:l,isLoading:i}=He(t),[c,n]=_.useState(null),h=we(),T=Se(),j=We(),P=ke(),R=be(),v=Xe(),$=()=>{n(null),a(r.trim())};return e.jsx(B,{children:e.jsxs(G,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(K,{placeholder:"Search by email...",value:r,onChange:x=>s(x.target.value),onKeyDown:x=>x.key==="Enter"&&$(),className:"max-w-sm"}),e.jsxs(p,{onClick:$,disabled:i,className:"gap-2",children:[e.jsx(Qe,{className:"h-4 w-4"})," Search"]})]}),i&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Searchingâ¦"}),t&&!i&&!l&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:['No learner found for "',t,'"']}),l&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-foreground",children:l.fullName}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.email})]}),e.jsxs(g,{variant:l.guid?"default":"destructive",children:["GUID: ",l.guid?as(l.guid):"NULL"]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Local Score"}),e.jsx("p",{className:"text-lg font-bold text-foreground",children:l.localScore??"â"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Calculated At"}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:J(l.calculatedAt)})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Live Score (Signal)"}),e.jsx("p",{className:"text-lg font-bold text-foreground",children:c?c.status==="processing"?"processingâ¦":c.score??"â":"â"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Peak Score"}),e.jsx("p",{className:"text-lg font-bold text-foreground",children:c?c.peak:"â"}),c&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1",children:["as of ",J(c.fetchedAt)]})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[l.totalEvents," events (",l.pendingEvents," pending, ",l.failedEvents," failed)"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(p,{size:"sm",variant:"outline",onClick:()=>v.mutate(l.userId,{onSuccess:x=>{var L,f,N;n({score:(x==null?void 0:x.score)??null,peak:((f=(L=x==null?void 0:x.score_breakdown)==null?void 0:L.details)==null?void 0:f.peak_score)??0,status:(x==null?void 0:x.status)??"ready",fetchedAt:((N=x==null?void 0:x.score_breakdown)==null?void 0:N.calculated_at)??new Date().toISOString()})}}),disabled:v.isPending,className:"gap-1",children:[e.jsx(Ue,{className:"h-3 w-3"})," ",v.isPending?"Refreshingâ¦":"Refresh Score"]}),e.jsxs(p,{size:"sm",onClick:()=>h.mutate(l.userId),disabled:h.isPending,className:"gap-1",children:[e.jsx(X,{className:"h-3 w-3"})," Force Sync"]}),e.jsxs(p,{size:"sm",variant:"outline",onClick:()=>T.mutate(l.userId),disabled:T.isPending,className:"gap-1",children:[e.jsx(W,{className:"h-3 w-3"})," Force GUID"]}),e.jsxs(p,{size:"sm",variant:"outline",onClick:()=>j.mutate(l.userId),disabled:j.isPending,className:"gap-1",children:[e.jsx(Ne,{className:"h-3 w-3"})," Recalculate"]}),e.jsxs(p,{size:"sm",variant:"outline",onClick:()=>P.mutate(l.userId),disabled:P.isPending,className:"gap-1",children:[e.jsx(ve,{className:"h-3 w-3"})," Retry Failed"]}),e.jsxs(p,{size:"sm",variant:"outline",onClick:()=>R.mutate({target_user_id:l.userId,dry_run:!0,include_events:!0},{onSuccess:x=>{console.log("[Backfill DRY-RUN]",l.email,x)}}),disabled:R.isPending,className:"gap-1",children:[e.jsx(V,{className:"h-3 w-3"})," Dry-Run Backfill"]}),e.jsxs(p,{size:"sm",onClick:()=>R.mutate({target_user_id:l.userId,dry_run:!1,include_events:!0},{onSuccess:x=>{console.log("[Backfill LIVE]",l.email,x)}}),disabled:R.isPending,className:"gap-1",children:[e.jsx(V,{className:"h-3 w-3"})," Backfill Now"]})]})]})]})})},ds=()=>{const[r,s]=_.useState({status:"all",eventType:"",userSearch:"",page:0}),{data:t,isLoading:a}=Ve(r),{data:l}=Ze(),i=t?Math.ceil(t.totalCount/t.pageSize):0,c=n=>!n.sent_at&&!n.last_error?e.jsx(g,{className:"bg-amber-100 text-amber-800 border-amber-200",children:"Pending"}):n.last_error==="audit_only_not_sent"?e.jsx(g,{variant:"secondary",children:"Audit Only"}):n.last_error?e.jsx(g,{variant:"destructive",children:"Failed"}):e.jsx(g,{className:"bg-green-100 text-green-800 border-green-200",children:"Sent"});return e.jsx(B,{children:e.jsxs(G,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(ne,{value:r.status,onValueChange:n=>s(h=>({...h,status:n,page:0})),children:[e.jsx(ae,{className:"w-36",children:e.jsx(ie,{placeholder:"Status"})}),e.jsxs(le,{children:[e.jsx(A,{value:"all",children:"All"}),e.jsx(A,{value:"pending",children:"Pending"}),e.jsx(A,{value:"sent",children:"Sent"}),e.jsx(A,{value:"failed",children:"Failed"}),e.jsx(A,{value:"audit_only",children:"Audit Only"})]})]}),e.jsxs(ne,{value:r.eventType,onValueChange:n=>s(h=>({...h,eventType:n==="_all"?"":n,page:0})),children:[e.jsx(ae,{className:"w-44",children:e.jsx(ie,{placeholder:"Event Type"})}),e.jsxs(le,{children:[e.jsx(A,{value:"_all",children:"All Types"}),(l??[]).map(n=>e.jsx(A,{value:n,children:n},n))]})]}),e.jsx(K,{placeholder:"User ID...",value:r.userSearch,onChange:n=>s(h=>({...h,userSearch:n.target.value,page:0})),className:"w-48"})]}),e.jsx("div",{className:"rounded-md border overflow-auto",children:e.jsxs(ge,{children:[e.jsx(je,{children:e.jsxs(F,{children:[e.jsx(D,{children:"User"}),e.jsx(D,{children:"Event Type"}),e.jsx(D,{children:"Status"}),e.jsx(D,{children:"Created"}),e.jsx(D,{children:"Retry"}),e.jsx(D,{children:"Error"})]})}),e.jsx(ye,{children:a?e.jsx(F,{children:e.jsx(k,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"Loadingâ¦"})}):((t==null?void 0:t.events)??[]).length===0?e.jsx(F,{children:e.jsx(k,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No events found"})}):((t==null?void 0:t.events)??[]).map(n=>e.jsxs(F,{children:[e.jsx(k,{className:"text-sm",children:n.userEmail}),e.jsx(k,{children:e.jsx(g,{variant:"outline",children:n.event_type})}),e.jsx(k,{children:c(n)}),e.jsx(k,{className:"text-sm",children:J(n.created_at)}),e.jsx(k,{className:"text-sm",children:n.retry_count??0}),e.jsx(k,{className:"text-sm text-destructive max-w-[200px] truncate",children:n.last_error||"â"})]},n.id))})]})}),i>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Page ",r.page+1," of ",i," (",t==null?void 0:t.totalCount," total)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(p,{variant:"outline",size:"sm",disabled:r.page===0,onClick:()=>s(n=>({...n,page:n.page-1})),children:"Previous"}),e.jsx(p,{variant:"outline",size:"sm",disabled:r.page>=i-1,onClick:()=>s(n=>({...n,page:n.page+1})),children:"Next"})]})]})]})})},us=({open:r,onOpenChange:s})=>{const{data:t,isLoading:a}=Ye(r),l=we(),i=Se(),c=rs();return e.jsx(me,{open:r,onOpenChange:s,children:e.jsxs(xe,{className:"max-w-2xl max-h-[80vh] overflow-auto",children:[e.jsxs(he,{children:[e.jsxs(pe,{className:"flex items-center gap-2",children:[e.jsx(V,{className:"h-5 w-5"})," Learners Without GUID"]}),e.jsxs(fe,{children:[(t==null?void 0:t.length)??0," learners without a Signal Score GUID mapping"]})]}),t&&t.length>0&&e.jsxs(p,{className:"w-fit gap-2",onClick:()=>c.mutate(t.map(n=>n.userId)),disabled:c.isPending,children:[e.jsx(_e,{className:"h-4 w-4"}),c.isPending?"Syncing Allâ¦":"Sync All"]}),e.jsx("div",{className:"rounded-md border overflow-auto",children:e.jsxs(ge,{children:[e.jsx(je,{children:e.jsxs(F,{children:[e.jsx(D,{children:"Learner"}),e.jsx(D,{children:"Actions"})]})}),e.jsx(ye,{children:a?e.jsx(F,{children:e.jsx(k,{colSpan:2,className:"text-center py-6 text-muted-foreground",children:"Loadingâ¦"})}):(t??[]).length===0?e.jsx(F,{children:e.jsxs(k,{colSpan:2,className:"text-center py-6 text-muted-foreground",children:[e.jsx(De,{className:"h-5 w-5 inline mr-2 text-green-600"}),"All learners have GUIDs"]})}):(t??[]).map(n=>e.jsxs(F,{children:[e.jsxs(k,{children:[e.jsx("p",{className:"font-medium text-sm",children:n.fullName}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.email})]}),e.jsx(k,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(p,{size:"sm",variant:"outline",onClick:()=>l.mutate(n.userId),disabled:l.isPending,children:e.jsx(X,{className:"h-3 w-3"})}),e.jsx(p,{size:"sm",variant:"outline",onClick:()=>i.mutate(n.userId),disabled:i.isPending,children:e.jsx(W,{className:"h-3 w-3"})})]})})]},n.userId))})]})})]})})};export{st 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.