PageSourceSearch

https://timlive.ai/assets/Admin2-CAWgWt38.js

js timlive.ai collected 2026-10-05 15:25:47 UTC 54,406 bytes, 25 lines download raw bytes

1import{w as He,j as e,x as ce,s as g,B as $,r as w,a1 as Qe,a2 as We,Y as Le,L as me,v as qe,I as Be,b3 as Ye,b as oe,c as v}from"./index-DroIlAnG.js";import{u as E}from"./useQuery-COLDQlQn.js";import{C as f,a as p,b as y,d as N,c as Q}from"./card-BZnhme5w.js";import{T as ye,a as Ne,b as K,c as R}from"./tabs-DK6x8aqv.js";import{S as xe,a as ue,b as he,c as je,d as L}from"./select-CySwsSPf.js";import{A as Fe,a as Ie}from"./alert-_58y7eJK.js";import{D as ne,a as re,b as ze,c as De,e as Me}from"./dialog-CVtHWYLW.js";import{N as Ze}from"./Navigation-DoQPN0Tb.js";import{F as Je}from"./Footer-CGgk2roi.js";import{D as Xe}from"./dollar-sign-CRWCxmkL.js";import{P as Oe}from"./phone-xl-ZXpsK.js";import{S as $e}from"./star-CB804rFb.js";import{Z as ie}from"./zap-Cc-jDIQI.js";import{B as T}from"./badge-DVnJIDwf.js";import{E as es}from"./external-link-ChBaMdAY.js";import{T as ve}from"./trending-down-DSA1ksA5.js";import{T as ge,a as fe,b as te,c as z,d as pe,e as D}from"./table-DVUksU5P.js";import{C as Ue,a as ss,b as ts}from"./CostPerUnqualifiedLead-CPk3Hwr1.js";import{B as as}from"./building-2-CzoFgPZG.js";import{A as ns}from"./activity-oG0lKZQN.js";import{C as rs}from"./chevron-right-Bx_Po07v.js";import{V as is}from"./VapiAssistantConfig-DRVx8PV4.js";import{P as Ee}from"./phone-call-CTFJlbo-.js";import{T as ls}from"./trending-up-CRmHVOVj.js";import"./index-BqLubvU2.js";import"./Combination-BoyQcAjc.js";import"./index-Bqt3h5Wx.js";import"./check-4INTiBeu.js";import"./index-B6z00Jvh.js";import"./logo-6N7tb0Ef.js";import"./dropdown-menu-DH2G7yVT.js";import"./circle-DlU040-2.js";import"./plug-lsc80SvF.js";import"./file-text-BTvc3hAx.js";import"./circle-play-5tMj1KW6.js";import"./users-BPUhcVQz.js";import"./message-square-BUiot6Cf.js";import"./shield-DCV_omzi.js";import"./menu--r0AyGGo.js";import"./gauge-d4eB_3ce.js";import"./credit-card-kWhzSQZQ.js";import"./sun-CSfEtinW.js";import"./lead-B3_St7Ii.js";import"./collapsible-Bdra_8UE.js";import"./index-CupVxSmf.js";import"./bot-BG7YjINk.js";import"./plus-CLA4_AtY.js";import"./pen-BDObRqqv.js";import"./trash-2-BXrCRVmm.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 Pe=He("ChartNoAxesColumnIncreasing",[["line",{x1:"12",x2:"12",y1:"20",y2:"10",key:"1vz5eb"}],["line",{x1:"18",x2:"18",y1:"20",y2:"4",key:"cun8e5"}
6],["line",{x1:"6",x2:"6",y1:"20",y2:"16",key:"hq0ia6"}]]);function os({timeRange:d,orgId:i}){var c,x,k,_,U,P,V,W,X;const{data:r,isLoading:m}=E({queryKey:["analytics-overview",d,i],queryFn:async()=>{const S=d==="daily"||d==="all"?"call_analytics_all_time":`call_analytics_${d}`;let A=g.from(S).select("*");i&&(A=A.eq("org_id",i));const{data:C,error:Y}=await A.single();if(Y)throw Y;return C}}),{data:a}=E({queryKey:["daily-kpis",i],queryFn:async()=>{let S=g.from("daily_kpis").select("*").order("day",{ascending:!1}).limit(1);i&&(S=S.eq("org_id",i));const{data:A,error:C}=await S.single();if(C)throw C;return A}}),{data:s}=E({queryKey:["vapi-costs",d,i],queryFn:async()=>{const{data:S,error:A}=await g.rpc("get_vapi_costs",{p_time_range:d,p_org_id:i||null});if(A)throw A;const C=(S==null?void 0:S[0])||{total_cost:0,total_duration:0,call_count:0,avg_cost_per_call:0,avg_cost_per_minute:0};return{totalCost:Number(C.total_cost)||0,totalDuration:Number(C.total_duration)||0,callCount:Number(C.call_count)||0,avgCostPerCall:Number(C.avg_cost_per_call)||0,avgCostPerMinute:Number(C.avg_cost_per_minute)||0}}});return m?e.jsx("div",{className:"text-center py-8",children:"Loading analytics..."}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(f,{className:"border-primary/50 bg-primary/5",children:[e.jsxs(p,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(y,{className:"text-sm font-medium",children:"VAPI Cost"}),e.jsx(Xe,{className:"h-4 w-4 text-primary"})]}),e.jsxs(N,{children:[e.jsxs("div",{className:"text-2xl font-bold text-primary",children:["$",((c=s==null?void 0:s.totalCost)==null?void 0:c.toFixed(2))||"0.00"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["$",((x=s==null?void 0:s.avgCostPerCall)==null?void 0:x.toFixed(2))||"0.00","/call • $",((k=s==null?void 0:s.avgCostPerMinute)==null?void 0:k.toFixed(2))||"0.00","/min"]})]})]}),e.jsxs(f,{children:[e.jsxs(p,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(y,{className:"text-sm font-medium",children:"Total Calls Analyzed"}),e.jsx(Oe,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(N,{children:[e.jsx("div",{className:"text-2xl font-bold",children:(r==null?void 0:r.total_calls)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(a==null?void 0:a.outbound_calls)||0," outbound today"]})]})]}),e.jsxs(f,{children:[e.jsxs(p,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(y,{className:"text-sm font-medium",children:"Avg Quality Score"}),e.jsx($e,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(N,{children:[e.jsx("div",{className:"text-2xl font-bold",children:((_=r==null?void 0:r.avg_quality)==null?void 0:_.toFixed(1))||"0.0"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Best: ",(r==null?void 0:r.best_call)||0," / Worst: ",(r==null?void 0:r.worst_call)||0]})]})]}),e.jsxs(f,{children:[e.jsxs(p,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(y,{className:"text-sm font-medium",children:"Marketing Energy"}),e.jsx(ie,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(N,{children:[e.jsx("div",{className:"text-2xl font-bold",children:((U=r==null?void 0:r.avg_marketing)==null?void 0:U.toFixed(1))||"0.0"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg marketing salience score"})]})]}),e.jsxs(f,{children:[e.jsxs(p,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(y,{className:"text-sm font-medium",children:"Failure Rate"}),e.jsx(ce,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(N,{children:[e.jsx("div",{className:"text-2xl font-bold",children:((P=r==null?void 0:r.avg_negative)==null?void 0:P.toFixed(1))||"0.0"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg negative vector score"})]})]}),e.jsxs(f,{children:[e.jsxs(p,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(y,{className:"text-sm font-medium",children:"Talk Time"}),e.jsx(Oe,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(N,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[Math.floor(((s==null?void 0:s.totalDuration)||0)/60),"m ",((s==null?void 0:s.totalDuration)||0)%60,"s"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.callCount)||0," total calls"]})]})]}),e.jsxs(f,{className:"md:col-span-2",children:[e.jsxs(p,{children:[e.jsx(y,{children:"Daily Activity"}),e.jsx(Q,{children:"Key performance indicators"})]}),e.jsxs(N,{className:"grid gap-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Answered Calls"}),e.jsx("span",{className:"text-sm font-medium",children:(a==null?void 0:a.answered_calls)||0})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Minutes Used"}),e.jsxs("span",{className:"text-sm font-medium",children:[Math.floor(((a==null?void 0:a.minutes_used)||0)/60)," min"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Inbound Calls"}),e.jsx("span",{className:"text-sm font-medium",children:(a==null?void 0:a.inbound_calls)||0})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Inbound Texts"}),e.jsx("span",{className:"text-sm font-medium",children:(a==null?void 0:a.inbound_texts)||0})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Newly Qualified"}),e.jsx("span",{className:"text-sm font-medium",children:(a==null?void 0:a.newly_qualified)||0})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Offers Made"}),e.jsx("span",{className:"text-sm font-medium",children:(a==null?void 0:a.offers_made)||0})]})]})]}),e.jsxs(f,{className:"md:col-span-2",children:[e.jsxs(p,{children:[e.jsx(y,{children:"Salience Breakdown"}),e.jsx(Q,{children:"Average scores across dimensions"})]}),e.jsxs(N,{className:"grid gap-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"AI Showcase"}),e.jsx("span",{className:"text-sm font-medium",children:((V=r==null?void 0:r.avg_showcase)==null?void 0:V.toFixed(1))||"0.0"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Training Score"}),e.jsx("span",{className:"text-sm font-medium",children:((W=r==null?void 0:r.avg_training)==null?void 0:W.toFixed(1))||"0.0"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Channel Friction"}),e.jsx("span",{className:"text-sm font-medium",children:((X=r==null?void 0:r.avg_friction)==null?void 0:X.toFixed(1))||"0.0"})]})]})]})]})}function cs({timeRange:d,orgId:i}){const{data:r,isLoading:m}=E({queryKey:["marketing-gems",d,i],queryFn:async()=>{let a=g.from("call_analytics").select("*, conversations(*), leads(address)").order("marketing_score",{ascending:!1}).limit(10);i&&(a=a.eq("org_id",i));const{data:s,error:c}=await a;if(c)throw c;return s}});return m?e.jsx("div",{className:"text-center py-8",children:"Loading marketing gems..."}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Marketing Power Moments"}),e.jsx("p",{className:"text-muted-foreground",children:"Top calls with highest marketing energy (80-100 = social media ready)"})]}),e.jsx("div",{className:"grid gap-4",children:r==null?void 0:r.map(a=>{var s;return e.jsxs(f,{children:[e.jsx(p,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(y,{className:"text-lg",children:((s=a.leads)==null?void 0:s.address)||"Unknown Property"}
6),e.jsx(Q,{children:new Date(a.analyzed_at).toLocaleString()})]}),e.jsxs(T,{variant:a.marketing_score>=80?"default":"secondary",children:["Marketing: ",a.marketing_score,"/100"]})]})}),e.jsxs(N,{className:"space-y-2",children:[e.jsx("p",{className:"text-sm",children:a.marketing_reason}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(T,{variant:"outline",children:["Quality: ",a.overall_quality_score,"/100"]}),e.jsxs(T,{variant:"outline",children:["AI Showcase: ",a.ai_showcase_score,"/100"]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"mt-2",children:[e.jsx(es,{className:"mr-2 h-4 w-4"}),"View Full Transcript"]})]})]},a.id)})})]})}function ds({timeRange:d,orgId:i}){const{data:r,isLoading:m}=E({queryKey:["training-needs",d,i],queryFn:async()=>{let a=g.from("call_analytics").select("*, conversations(*), leads(address)").order("training_score",{ascending:!1}).limit(10);i&&(a=a.eq("org_id",i));const{data:s,error:c}=await a;if(c)throw c;return s}});return m?e.jsx("div",{className:"text-center py-8",children:"Loading training needs..."}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Training Opportunities"}),e.jsx("p",{className:"text-muted-foreground",children:"Calls with issues that need addressing in TIM's training"})]}),e.jsx("div",{className:"grid gap-4",children:r==null?void 0:r.map(a=>{var s;return e.jsxs(f,{className:"border-orange-200 dark:border-orange-900",children:[e.jsx(p,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(y,{className:"text-lg flex items-center gap-2",children:[e.jsx(ce,{className:"h-5 w-5 text-orange-500"}),((s=a.leads)==null?void 0:s.address)||"Unknown Property"]}),e.jsx(Q,{children:new Date(a.analyzed_at).toLocaleString()})]}),e.jsxs(T,{variant:"destructive",children:["Training Score: ",a.training_score,"/100"]})]})}),e.jsxs(N,{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Issue Identified:"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a.training_reason}),a.negative_score<-20&&e.jsxs("div",{className:"mt-2 p-2 bg-red-50 dark:bg-red-950 rounded",children:[e.jsx("p",{className:"text-sm font-medium text-red-700 dark:text-red-400",children:"Failure Detected:"}),e.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:a.negative_reason})]})]})]},a.id)})})]})}function ms({timeRange:d,orgId:i}){const{data:r,isLoading:m}=E({queryKey:["ai-showcase",d,i],queryFn:async()=>{let a=g.from("call_analytics").select("*, conversations(*), leads(address)").order("ai_showcase_score",{ascending:!1}).limit(10);i&&(a=a.eq("org_id",i));const{data:s,error:c}=await a;if(c)throw c;return s}});return m?e.jsx("div",{className:"text-center py-8",children:"Loading AI showcase moments..."}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"AI Showcase Moments"}),e.jsx("p",{className:"text-muted-foreground",children:"TIM flexing schema & state awareness, memory, and reasoning"})]}),e.jsx("div",{className:"grid gap-4",children:r==null?void 0:r.map(a=>{var s;return e.jsxs(f,{className:"border-purple-200 dark:border-purple-900",children:[e.jsx(p,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(y,{className:"text-lg flex items-center gap-2",children:[e.jsx(ie,{className:"h-5 w-5 text-purple-500"}),((s=a.leads)==null?void 0:s.address)||"Unknown Property"]}),e.jsx(Q,{children:new Date(a.analyzed_at).toLocaleString()})]}),e.jsxs(T,{className:"bg-purple-500",children:["AI Showcase: ",a.ai_showcase_score,"/100"]})]})}),e.jsxs(N,{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"What TIM Did:"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a.ai_showcase_reason}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(T,{variant:"outline",children:["Quality: ",a.overall_quality_score,"/100"]}),e.jsxs(T,{variant:"outline",children:["Marketing: ",a.marketing_score,"/100"]})]})]})]},a.id)})})]})}function xs({timeRange:d,orgId:i}){const{data:r,isLoading:m}=E({queryKey:["objection-mastery",d,i],queryFn:async()=>{let s=g.from("call_analytics").select("*, conversations(*), leads(address)").order("objection_top_score",{ascending:!1}).limit(20);i&&(s=s.eq("org_id",i));const{data:c,error:x}=await s;if(x)throw x;return c}});if(m)return e.jsx("div",{className:"text-center py-8",children:"Loading objection handling data..."});const a=r==null?void 0:r.reduce((s,c)=>{const x=c.objection_top_type||"other";return s[x]||(s[x]=[]),s[x].push(c),s},{});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Objection Handling Mastery"}),e.jsx("p",{className:"text-muted-foreground",children:"Best and worst objection responses by type"})]}),e.jsxs(ye,{defaultValue:Object.keys(a||{})[0],children:[e.jsx(Ne,{children:Object.keys(a||{}).map(s=>e.jsx(K,{value:s,className:"capitalize",children:s},s))}),Object.entries(a||{}).map(([s,c])=>e.jsx(R,{value:s,className:"space-y-4",children:c.map(x=>{var k;return e.jsxs(f,{children:[e.jsx(p,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(y,{className:"text-lg",children:((k=x.leads)==null?void 0:k.address)||"Unknown Property"}
6),e.jsx(Q,{children:new Date(x.analyzed_at).toLocaleString()})]}),e.jsxs(T,{variant:x.objection_top_score>=70?"default":"secondary",children:["Score: ",x.objection_top_score,"/100"]})]})}),e.jsx(N,{children:e.jsx("p",{className:"text-sm",children:x.objection_top_reason})})]},x.id)})},s))]})]})}function us({timeRange:d,orgId:i}){const{data:r,isLoading:m}=E({queryKey:["failure-modes",d,i],queryFn:async()=>{let s=g.from("call_analytics").select("*, conversations(*), leads(address)").lt("negative_score",-20).order("negative_score",{ascending:!0}).limit(10);i&&(s=s.eq("org_id",i));const{data:c,error:x}=await s;if(x)throw x;return c}}),{data:a}=E({queryKey:["channel-friction",d,i],queryFn:async()=>{let s=g.from("call_channel_friction").select("*, leads(address)").order("friction_score",{ascending:!0}).limit(10);if(i){const{data:k}=await g.from("leads").select("id").eq("org_id",i);k&&(s=s.in("lead_id",k.map(_=>_.id)))}const{data:c,error:x}=await s;if(x)throw x;return c}});return m?e.jsx("div",{className:"text-center py-8",children:"Loading failure analysis..."}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Failure Modes & Negative Vectors"}),e.jsx("p",{className:"text-muted-foreground",children:"Critical failures, hallucinations, state drifts, and contradictions"})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-xl font-semibold mb-4 flex items-center gap-2",children:[e.jsx(ce,{className:"h-5 w-5 text-red-500"}),"Call Failures"]}),e.jsx("div",{className:"grid gap-4",children:r==null?void 0:r.map(s=>{var c;return e.jsxs(f,{className:"border-red-200 dark:border-red-900",children:[e.jsx(p,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(y,{className:"text-lg",children:((c=s.leads)==null?void 0:c.address)||"Unknown Property"}),e.jsx(Q,{children:new Date(s.analyzed_at).toLocaleString()})]}),e.jsxs(T,{variant:"destructive",children:["Failure: ",s.negative_score,"/100"]})]})}),e.jsxs(N,{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-red-700 dark:text-red-400",children:"Failure Type:"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s.negative_reason}),e.jsx("div",{className:"flex gap-2 mt-2",children:e.jsxs(T,{variant:"outline",children:["Quality: ",s.overall_quality_score,"/100"]})})]})]},s.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-xl font-semibold mb-4 flex items-center gap-2",children:[e.jsx(ve,{className:"h-5 w-5 text-orange-500"}),"Cross-Channel Friction"]}),e.jsx("div",{className:"grid gap-4",children:a==null?void 0:a.map(s=>{var c,x;return e.jsxs(f,{className:"border-orange-200 dark:border-orange-900",children:[e.jsx(p,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(y,{className:"text-lg",children:((c=s.leads)==null?void 0:c.address)||"Unknown Property"}),e.jsx(Q,{children:new Date(s.created_at).toLocaleString()})]}),e.jsxs(T,{variant:"destructive",children:["Friction: ",s.friction_score,"/100"]})]})}),e.jsxs(N,{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-orange-700 dark:text-orange-400",children:"Contradiction:"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s.friction_reason}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Involves ",((x=s.conversation_ids)==null?void 0:x.length)||0," conversations"]})]})]},s.id)})})]})]})}function hs({orgId:d}){var Y;const[i,r]=w.useState(null),{data:m,isLoading:a}=E({queryKey:["token-pools",d],queryFn:async()=>{let t=g.from("token_pools").select(`
7          *,
8          organizations!inner(name)
9        `).order("balance",{ascending:!0});d&&(t=t.eq("org_id",d));const{data:l,error:h}=await t;if(h)throw h;return l}}),{data:s,isLoading:c}=E({queryKey:["token-transactions",d],queryFn:async()=>{let t=g.from("token_transactions").select(`
10          *,
11          organizations!inner(name)
12        `).order("created_at",{ascending:!1}).limit(500);d&&(t=t.eq("org_id",d));const{data:l,error:h}=await t;if(h)throw h;return l}}),{data:x}=E({queryKey:["org-subscriptions",d],queryFn:async()=>{let t=g.from("org_subscriptions").select(`
13          *,
14          organizations!inner(name),
15          subscription_tiers!inner(name, tokens_included, price_cents)
16        `).eq("status","active");d&&(t=t.eq("org_id",d));const{data:l,error:h}=await t;if(h)throw h;return l}}),k=["call_attempt","call_minute","sms_send","sms_receive","lead_ingest","enrichment"],_=(s==null?void 0:s.reduce((t,l)=>{if(Number(l.amount)<0&&k.includes(l.transaction_type)){const h=l.transaction_type;t[h]=(t[h]||0)+Math.abs(Number(l.amount))}return t},{}))||{},U=(s==null?void 0:s.reduce((t,l)=>{if(Number(l.amount)<0&&k.includes(l.transaction_type)){const h=l.transaction_type,j=l.source||"unknown";
16t[h]||(t[h]={}),t[h][j]=(t[h][j]||0)+Math.abs(Number(l.amount))}return t},{}))||{},P=(s==null?void 0:s.filter(t=>Number(t.amount)<0).reduce((t,l)=>t+Math.abs(Number(l.amount)),0))||0;s!=null&&s.filter(t=>Number(t.amount)>0).reduce((t,l)=>t+Number(l.amount),0);const V=(m==null?void 0:m.reduce((t,l)=>t+Number(l.balance),0))||0,W=(m==null?void 0:m.length)||0,X=(m==null?void 0:m.filter(t=>Number(t.balance)<10).length)||0;if(a||c)return e.jsx("div",{className:"text-muted-foreground",children:"Loading token data..."});const S={call_attempt:"Call Attempts",call_minute:"Call Minutes",sms_send:"SMS Sends",sms_receive:"SMS Received",lead_ingest:"Lead Ingests",enrichment:"Enrichments"},A={call_attempt:"📞",call_minute:"⏱️",sms_send:"💬",sms_receive:"📩",lead_ingest:"📥",enrichment:"🔍"},C={"vapi-events":"VAPI Events","vapi-webhook":"VAPI Webhook","send-sms":"Send SMS","process-pending-sms":"Pending SMS Processor","bulk-lead-ingest":"Bulk Import","if3-ingest":"IF3 Ingest","n8n-ingest-lead":"N8N Ingest",unknown:"Unknown Source"};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs(f,{children:[e.jsxs(p,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(y,{className:"text-sm font-medium",children:"Total Balance"}),e.jsx(Ue,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(N,{children:[e.jsx("div",{className:"text-2xl font-bold",children:V.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"tokens across all orgs"})]})]}),e.jsxs(f,{children:[e.jsxs(p,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(y,{className:"text-sm font-medium",children:"Total Burned"}),e.jsx(ve,{className:"h-4 w-4 text-destructive"})]}),e.jsxs(N,{children:[e.jsx("div",{className:"text-2xl font-bold text-destructive",children:P.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"tokens consumed"})]})]}),e.jsxs(f,{children:[e.jsxs(p,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(y,{className:"text-sm font-medium",children:"Active Orgs"}),e.jsx(as,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(N,{children:[e.jsx("div",{className:"text-2xl font-bold",children:W}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with token pools"})]})]}),e.jsxs(f,{children:[e.jsxs(p,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(y,{className:"text-sm font-medium",children:"Low Balance"}),e.jsx(ns,{className:"h-4 w-4 text-warning"})]}),e.jsxs(N,{children:[e.jsx("div",{className:"text-2xl font-bold text-warning",children:X}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"orgs below 10 tokens"})]})]})]}),e.jsxs(f,{children:[e.jsx(p,{children:e.jsxs(y,{className:"flex items-center gap-2",children:[e.jsx(ie,{className:"h-5 w-5"}),"Burns by Category",i&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>r(null),className:"ml-auto",children:[e.jsx(Qe,{className:"h-4 w-4 mr-1"}),"Back to categories"]})]})}),e.jsx(N,{children:Object.keys(_).length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No token burns recorded yet"}):i?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4 text-muted-foreground",children:[e.jsx("span",{className:"text-2xl",children:A[i]||"🔹"}),e.jsx("span",{className:"font-medium",children:S[i]||i}),e.jsxs("span",{className:"text-sm",children:["(",(Y=_[i])==null?void 0:Y.toLocaleString()," tokens total)"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Object.entries(U[i]||{}).map(([t,l])=>e.jsxs("div",{className:"p-4 rounded-lg border bg-card text-center",children:[e.jsx("div",{className:"text-lg font-bold",children:l.toLocaleString()}),e.jsx("div",{className:"text-sm text-muted-foreground",children:C[t]||t}),e.jsxs("div",{className:"text-xs text-muted-foreground/70 mt-1",children:[(l/_[i]*100).toFixed(1),"%"]})]},t))})]}
16):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:Object.entries(_).map(([t,l])=>e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 text-center cursor-pointer hover:bg-muted transition-colors group",onClick:()=>r(t),children:[e.jsx("div",{className:"text-2xl mb-1",children:A[t]||"🔹"}),e.jsx("div",{className:"text-xl font-bold",children:l.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:S[t]||t}),e.jsxs("div",{className:"flex items-center justify-center mt-2 text-xs text-muted-foreground/70 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(rs,{className:"h-3 w-3"}),e.jsx("span",{children:"View sources"})]})]},t))})})]}),e.jsxs(f,{children:[e.jsx(p,{children:e.jsx(y,{children:"Organization Token Balances"})}),e.jsx(N,{children:!m||m.length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No token pools found"}):e.jsxs(ge,{children:[e.jsx(fe,{children:e.jsxs(te,{children:[e.jsx(z,{children:"Organization"}),e.jsx(z,{children:"Balance"}),e.jsx(z,{children:"Period"}),e.jsx(z,{children:"Status"})]})}),e.jsx(pe,{children:m.map(t=>{var l;return e.jsxs(te,{children:[e.jsx(D,{className:"font-medium",children:((l=t.organizations)==null?void 0:l.name)||"Unknown"}),e.jsx(D,{children:e.jsx("span",{className:Number(t.balance)<10?"text-destructive font-bold":"",children:Number(t.balance).toLocaleString()})}),e.jsx(D,{className:"text-sm text-muted-foreground",children:t.period_start&&t.period_end?`${new Date(t.period_start).toLocaleDateString()} - ${new Date(t.period_end).toLocaleDateString()}`:"N/A"}),e.jsx(D,{children:Number(t.balance)<10?e.jsx(T,{variant:"destructive",children:"Low"}):Number(t.balance)<25?e.jsx(T,{variant:"secondary",children:"Medium"}):e.jsx(T,{variant:"default",children:"Good"})})]},t.id)})})]})})]}),x&&x.length>0&&e.jsxs(f,{children:[e.jsx(p,{children:e.jsx(y,{children:"Active Subscriptions"})}),e.jsx(N,{children:e.jsxs(ge,{children:[e.jsx(fe,{children:e.jsxs(te,{children:[e.jsx(z,{children:"Organization"}),e.jsx(z,{children:"Tier"}),e.jsx(z,{children:"Tokens Included"}),e.jsx(z,{children:"Price"}),e.jsx(z,{children:"Period"})]})}),e.jsx(pe,{children:x.map(t=>{var l,h,j,q;return e.jsxs(te,{children:[e.jsx(D,{className:"font-medium",children:((l=t.organizations)==null?void 0:l.name)||"Unknown"}),e.jsx(D,{children:e.jsx(T,{variant:"outline",className:"capitalize",children:(h=t.subscription_tiers)==null?void 0:h.name})}),e.jsx(D,{children:(j=t.subscription_tiers)==null?void 0:j.tokens_included}),e.jsxs(D,{children:["$",(((q=t.subscription_tiers)==null?void 0:q.price_cents)/100).toFixed(2)]}),e.jsx(D,{className:"text-sm text-muted-foreground",children:t.current_period_start&&t.current_period_end?`${new Date(t.current_period_start).toLocaleDateString()} - ${new Date(t.current_period_end).toLocaleDateString()}`:"N/A"})]},t.id)})})]})})]}),e.jsxs(f,{children:[e.jsx(p,{children:e.jsx(y,{children:"Recent Token Transactions"})}),e.jsx(N,{children:!s||s.length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No transactions recorded yet"}):e.jsxs(ge,{children:[e.jsx(fe,{children:e.jsxs(te,{children:[e.jsx(z,{children:"Organization"}),e.jsx(z,{children:"Type"}),e.jsx(z,{children:"Amount"}),e.jsx(z,{children:"Category"}),e.jsx(z,{children:"Balance After"}),e.jsx(z,{children:"When"})]})}),e.jsx(pe,{children:s.slice(0,50).map(t=>{var l;return e.jsxs(te,{children:[e.jsx(D,{className:"font-medium",children:((l=t.organizations)==null?void 0:l.name)||"Unknown"}),e.jsx(D,{children:e.jsx(T,{variant:Number(t.amount)<0?"destructive":"default",children:Number(t.amount)<0?"burn":"credit"})}),e.jsxs(D,{className:Number(t.amount)<0?"text-destructive":"text-green-600",children:[Number(t.amount)<0?"-":"+",Math.abs(Number(t.amount)).toLocaleString()]}),e.jsx(D,{children:e.jsxs("span",{className:"text-sm",children:[A[t.transaction_type]||""," ",S[t.transaction_type]||t.transaction_type||"N/A"]})}),e.jsx(D,{children:Number(t.balance_after).toLocaleString()}),e.jsx(D,{className:"text-sm text-muted-foreground",children:We(new Date(t.created_at),{addSuffix:!0})})]},t.id)})})]})})]})]})}function js({open:d,onOpenChange:i,leadId:r,results:m,onApplyUpdates:a,onTestCall:s}){const[c,x]=w.useState({}),[k,_]=w.useState(!1),[U,P]=w.useState(""),[V,W]=w.useState("");w.useEffect(()=>{if(m!=null&&m.field_updates){const j={};
16Object.entries(m.field_updates).forEach(([q,o])=>{j[q]=o.value}),x(j)}},[m]);const X=(j,q)=>{x(o=>({...o,[j]:q}))},S=()=>{r&&a(r,c)},A=()=>{_(!0)},C=()=>{!r||!U.trim()||!V.trim()||(s(r,V,U),_(!1),P(""),W(""))};if(!m)return null;const{context:Y,field_updates:t,metadata:l}=m,h=Y||{};return e.jsxs(ne,{open:d,onOpenChange:i,children:[e.jsxs(re,{className:"max-w-6xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(ze,{children:e.jsx(De,{children:"Lead Analysis Results"})}),e.jsxs(ye,{defaultValue:"intelligence",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Ne,{className:"grid w-full grid-cols-3",children:[e.jsxs(K,{value:"intelligence",children:["Intelligence Bundle (",Object.keys(h).length,")"]}),e.jsxs(K,{value:"fields",children:["Field Updates (",t?Object.keys(t).length:0,")"]}),e.jsx(K,{value:"metadata",children:"Metadata"})]}),e.jsx(R,{value:"intelligence",className:"flex-1 overflow-hidden",children:e.jsx(Le,{className:"h-[60vh] pr-4",children:e.jsx("div",{className:"space-y-4",children:Object.entries(h).map(([j,q])=>j==="lead_snapshot"||j==="metadata"?null:e.jsxs(f,{children:[e.jsx(p,{className:"pb-3",children:e.jsx(y,{className:"text-sm font-medium",children:j.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")})}),e.jsx(N,{children:e.jsx("pre",{className:"text-sm whitespace-pre-wrap font-mono bg-muted p-3 rounded-md",children:typeof q=="string"?q:JSON.stringify(q,null,2)})})]},j))})})}),e.jsx(R,{value:"fields",className:"flex-1 overflow-hidden",children:t?e.jsx(Le,{className:"h-[60vh] pr-4",children:e.jsx("div",{className:"space-y-3",children:Object.entries(t).map(([j,q])=>{const o=q.confidence||0,B=o>.8?"bg-green-500":o>.6?"bg-yellow-500":"bg-red-500";return e.jsxs("div",{className:"border rounded-lg p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(me,{className:"text-sm font-semibold",children:j.split("_").map(se=>se.charAt(0).toUpperCase()+se.slice(1)).join(" ")}),e.jsxs(T,{className:`${B} text-white`,children:[(o*100).toFixed(0),"% confidence"]})]}),e.jsx(qe,{value:c[j]||"",onChange:se=>
16X(j,se.target.value),className:"min-h-[60px] font-mono text-sm",placeholder:"No value"})]},j)})})}):e.jsx("div",{className:"flex items-center justify-center h-[60vh] text-muted-foreground",children:"No field updates available. Analysis was not run in extraction mode."})}),e.jsx(R,{value:"metadata",className:"flex-1",children:e.jsxs(f,{children:[e.jsxs(p,{children:[e.jsx(y,{children:"Analysis Metadata"}),e.jsx(Q,{children:"Processing statistics and data quality metrics"})]}),e.jsxs(N,{className:"space-y-4",children:[h.metadata&&e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Generated At"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:new Date(h.metadata.generated_at).toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Fields Analyzed"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h.metadata.total_fields_analyzed})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Conversations Analyzed"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h.metadata.total_conversations_analyzed})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Actions Analyzed"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h.metadata.total_actions_analyzed})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Master Notes Length"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[h.metadata.master_notes_length," characters"]})]})]}),l&&e.jsxs("div",{className:"mt-4 pt-4 border-t",children:[e.jsx("p",{className:"text-sm font-semibold mb-2",children:"Extraction Stats"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Conversations Processed"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.conversations_analyzed})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Fields Updated"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.fields_updated})]})]})]})]})]})})]}),e.jsxs(Me,{className:"gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),m.context&&e.jsxs($,{variant:"secondary",onClick:A,disabled:!r,children:[e.jsx(Ee,{className:"mr-2 h-4 w-4"}),"Test This Context"]}),t&&e.jsxs($,{onClick:S,disabled:!r,children:["Apply ",Object.keys(c).length," Field Updates"]})]})]}),e.jsx(ne,{open:k,onOpenChange:_,children:e.jsxs(re,{className:"sm:max-w-md",children:[e.jsx(ze,{children:e.jsx(De,{children:"Test Call Setup"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(me,{htmlFor:"test-action",children:"Action Description"}),e.jsx(qe,{id:"test-action",placeholder:"e.g., Follow up on offer discussion, address concerns about timeline",value:V,onChange:j=>W(j.target.value),className:"min-h-[100px]"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"What should Tim accomplish on this call?"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(me,{htmlFor:"test-phone",children:"Your Phone Number"}),e.jsx(Be,{id:"test-phone",type:"tel",placeholder:"+1234567890",value:U,onChange:j=>P(j.target.value)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Tim will call this number as if you are the lead"})]})]}),e.jsxs(Me,{children:[e.jsx($,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsxs($,{onClick:C,disabled:!U.trim()||!V.trim(),children:[e.jsx(Ee,{className:"mr-2 h-4 w-4"}),"Generate Context"]})]})]})})]})}function mt(){var Se,Ce,Te,ke,Ae;const[d,i]=w.useState("daily"),[r,m]=w.useState(null),[a,s]=w.useState(""),[c,x]=w.useState(!1),[k,_]=w.useState(null),[U,P]=w.useState(!1),[V,W]=w.useState(null),[X,S]=w.useState(null),[A,C]=w.useState(""),Y=["📄 Tim is analyzing his full conversation history of voice ☎️ and text 📱💬...","🧠 TIM is generating his call notes to assist himself with his understanding of the lead's view point so he can communicate with maximum efficiency and handle dynamics that the seller might refer to.","⏳ Tim is refreshing his Lead Context 🌎, Awareness 👀 & Understanding of the Seller's situation and thought-processing-logic 🧠","You can build on your TIM Tech Intelligence by adding your ninja operator tips into tim's directives when he finishes his lead review 🤓 These Tips will help direct Tim with future leads as well! 💥","He's getting there... He reads EVERY word! 🤯","Tim is recalling what position the seller holds and preparing objection handling and value-creation strategies to use during his conversation and potential negotiations.â
16¤ï¸","Hi, it's me, Tim, I'm finishing summarizing my thoughts and awareness of the seller and their situation and view-point, I'll touch base with you in just 1 minute to make sure you agree that I'm fully-prepared for this important call - and can add any finishing touches to our pre-call notes #ShakeAndBake 🐺","Sorry, one last thing - our COO, Ghost 👻, requires that I turn in all of my brain activity so that he can train me in our TIMTech Sales meetings. I just need to run these by his desk in the metaTimworld and I'll be right to you, Boss - Let's go get this deal! 💵","This may take another minute or two (don't abandon/re-run this process unless it takes more than 5 minutes - assuming you are on a good wifi connection.) - Tim 🪄",`Hang on one sec — I'm just pulling up my notes.
17Real estate moves fast… kind of like contractors 🔨 when you don't need them. 🤣`,`Give me a moment to get everything up.
18I promise I'm faster than the HOA approving a paint color. 🎨🏡`,`One second — loading your property details…
19Unlike Zillow, I won't make up the price. 💀`,`Just a moment — organizing my notes… 🗒️
20I like to stay more buttoned-up than a landlord on rent-collection day 🕺🏽.`,`Let me pull this up…
21I'm pretty quick — definitely quicker than a city inspector. 🐌`,`One sec — pulling up the numbers…
22They told me to say I use TimTech, but between you and me, I still drink coffee first. ☕️`,`Hold on a sec — checking the details here…
23If patience was equity, you'd already have a cash-out refi. 🏡💰`,"Loading now — don't worry, I run faster than a retail seller running from a lowball offer. 🫨",`One moment — pulling up everything…
24I'd say my system is faster than escrow, but that's a low bar. 🥱`],[t]=w.useState(()=>{const n=[...Y];for(let u=n.length-1;u>0;u--){const b=Math.floor(Math.random()*(u+1));[n[u],n[b]]=[n[b],n[u]]}return n});w.useEffect(()=>{if(!c){C("");return}C(t[0]);let n=0;const u=setInterval(()=>{n=(n+1)%t.length,C(t[n])},7e3);return()=>clearInterval(u)},[c,t]);const{data:l}=E({queryKey:["organizations"],queryFn:async()=>{const{data:n,error:u}=await g.from("organizations").select("id, name").order("name");if(u)throw u;return n}}),h=async()=>{try{v.info("Starting call analysis...");const{data:n,error:u}=await g.functions.invoke("analyze-calls-delta-loop",{body:{analyze_all:!1}});if(u)throw u;n.remaining>0?v.warning(`Partial analysis: ${n.processed}/${n.total} processed. ${n.remaining} remaining.`):v.success(`Analysis complete! Processed ${n.processed} conversations`)}catch(n){console.error("Error running analysis:",n),v.error("Failed to run analysis")}},j=async()=>{try{v.info("Starting historical analysis...");let n=0,u=0,b=1,F=0;const M=100;for(;b>0&&F<M;){F++;const{data:I,error:G}=await g.functions.invoke("analyze-calls-delta-loop",{body:{analyze_all:!0}});if(G)throw G;n+=I.processed,u+=I.errors,b=I.remaining||0,v.info(`Progress: ${n} analyzed, ${b} remaining...`,{id:"historical-progress"}),b>0&&await new Promise(Z=>setTimeout(Z,1e3))}F>=M?v.warning(`Analysis stopped at iteration limit. Processed ${n}, ${u} errors.`):v.success(`Historical analysis complete! Processed ${n} conversations, ${u} errors`,{id:"historical-progress"})}catch(n){console.error("Error running historical analysis:",n),v.error("Failed to run historical analysis")}},q=async()=>{var u,b;_(null);const n=a.trim();if(!n){_("Please enter a lead phone number or ID");return}x(!0);try{const F=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n);let M=g.from("leads").select("*");if(F)M=M.eq("id",n);else{const Ge=n.replace(/\D/g,"").replace(/^1/,"");M=M.eq("phone_number",Ge)}const{data:I,error:G}=await M.maybeSingle();if(G)throw new Error(`Error looking up lead: ${G.message}`);if(!I)throw new Error(`No lead found with ${F?"ID":"phone number"}: ${n}`);v.info(`Analyzing lead: ${I.first_name||"Unknown"} ${I.last_name||""}`),console.log("🚀 Step 1/2: Generating summaries...");const Z=new AbortController,H=setTimeout(()=>Z.abort(),18e4),{data:ee,error:O}=await g.functions.invoke("generate-custom-call-summaries",{body:{leadId:I.id},signal:Z.signal});if(clearTimeout(H),O)throw console.error("Summaries error:",O),(u=O.message)!=null&&u.includes("aborted")?new Error("Summaries generation timed out. Please try again."):O;if(!ee.success)throw new Error("Failed to generate summaries");console.log("✅ Step 1/2 complete: Summaries generated"),console.log("🚀 Step 2/2: Generating call bundle...");const ae=new AbortController,de=setTimeout(()=>ae.abort(),18e4),{data:J,error:le}=await g.functions.invoke("generate-custom-call-bundle",{body:{conversationSummary:ee.conversationSummary,actionSummary:ee.actionSummary,leadSlimSummary:ee.leadSlimSummary,masterNotesSummary:ee.masterNotesSummary,actionDescription:"Admin test analysis - extract all fields and generate intelligence bundle",extractFields:!0},signal:ae.signal});if(clearTimeout(de),le)throw console.error("Bundle error:",le),(b=le.message)!=null&&b.includes("aborted")?new Error("Bundle generation timed out. Please try again."):le;console.log("✅ Step 2/2 complete: Bundle generated"),W(I.id),S(J),P(!0),v.success("Analysis complete - review results")}catch(F){console.error("Error analyzing lead:",F),_(F instanceof Error?F.message:"Unknown error"),v.error("Failed to analyze lead")}finally{x(!1)}},[o,B]=w.useState(null),[se,be]=w.useState(!1),[we,_e]=w.useState(!1),Ve=async(n,u,b)=>{var F,M,I,G,Z;be(!0);try{v.info("Generating call context..."),console.log("🚀 Step 1/2: Generating summaries...");const H=new AbortController,ee=setTimeout(()=>H.abort(),24e4),O=await g.functions.invoke("generate-custom-call-summaries",{body:{leadId:n},signal:H.signal});if(clearTimeout(ee),O.error)throw(F=O.error.message)!=null&&F.includes("aborted")?new Error("Summaries generation timed out. Please try again."):O.error;if(!((M=O.data)!=null&&M.success))throw new Error("Summaries generation failed");console.log("✅ Step 1/2 complete: Summaries generated"),console.log("🚀 Step 2/2: Generating call bundle...");const ae=new AbortController,de=setTimeout(()=>ae.abort(),24e4),J=await g.functions.invoke("generate-custom-call-bundle",{body:{conversationSummary:O.data.conversationSummary,actionSummary:O.data.actionSummary,leadSlimSummary:O.data.leadSlimSummary,masterNotesSummary:O.data.masterNotesSummary,actionDescription:u,extractFields:!1},signal:ae.signal});if(clearTimeout(de),J.error)throw(I=J.error.message)!=null&&I.includes("aborted")?new Error("Bundle generation timed out. Please try again."):J.error;if(!((G=J.data)!=null&&G.success)||!((Z=J.data)!=null&&Z.context))throw new Error("Bundle generation failed or missing context");console.log("✅ Step 2/2 complete: Bundle generated"),B({originalLeadId:n,phoneNumber:b,customInstru
24ctions:u,generatedContext:J.data.context,editedContext:J.data.context,scheduledMinutes:1}),v.success("Context generated - review before scheduling"),P(!1)}catch(H){console.error("Error generating test context:",H),v.error(H.message||"Failed to generate context")}finally{be(!1)}},Ke=async()=>{if(o){_e(!0);try{const{data:{user:n}}=await g.auth.getUser();if(!n)throw new Error("Not authenticated");const{data:u,error:b}=await g.from("leads").select("*").eq("id",o.originalLeadId).single();if(b)throw b;const F=o.phoneNumber.replace(/\D/g,"").replace(/^1/,"");v.info("Cloning lead...");const{data:M,error:I}=await g.from("leads").insert({...u,id:void 0,phone_number:F,user_id:n.id,first_name:`TEST_${u.first_name||"Lead"}`,notes:`[TEST CLONE] Original: ${o.originalLeadId}
25${u.notes||""}`,source:"test_call",created_at:void 0,updated_at:void 0}).select().single();if(I)throw I;v.info("Scheduling call action...");const G=new Date(Date.now()+o.scheduledMinutes*6e4).toISOString(),{data:Z,error:H}=await g.from("actions").insert({lead_id:M.id,user_id:n.id,org_id:u.org_id,action_type:"call",description:o.editedContext.action_description||o.customInstructions,ai_generated_description:!0,status:"pending",scheduled_at:G,respect_business_hours:!1,metadata:o.editedContext,created_by:"admin2:test_call",creation_context:{origin_reason:"admin_test_call",handler:"Admin2",created_via:"admin_test_call_tool",why:"Operator ran a test call against a cloned lead from the Admin2 console"}}).select().single();if(H)throw H;v.success(`Test call scheduled! Lead: ${M.id}, Action: ${Z.id}`),B(null)}catch(n){console.error("Error scheduling test call:",n),v.error(n.message||"Failed to schedule test call")}finally{_e(!1)}}},Re=async(n,u)=>{try{const{error:b}=await g.from("leads").update(u).eq("id",n);if(b)throw b;v.success(`Updated ${Object.keys(u).length} fields`),P(!1),s(""),S(null)}catch(b){console.error("Error applying updates:",b),v.error("Failed to apply updates")}};return e.jsx(Ye,{children:e.jsxs("div",{className:"min-h-screen flex flex-col",children:[e.jsx(Ze,{}),e.jsxs("div",{className:"container mx-auto p-6 space-y-6 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Δ-Loop Analytics"}),e.jsx("p",{className:"text-muted-foreground",children:"TIM's cognitive analytics engine — turn-level salience, cross-channel friction, energy scoring"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{onClick:h,variant:"outline",children:[e.jsx(ie,{className:"mr-2 h-4 w-4"}),"Analyze Last 24h"]}),e.jsxs($,{onClick:j,variant:"outline",children:[e.jsx(Pe,{className:"mr-2 h-4 w-4"}),"Analyze All History"]})]})]}),e.jsx(is,{}),e.jsxs(f,{className:"border-amber-500/30 bg-amber-500/5",children:[e.jsx(p,{className:"pb-2",children:e.jsx(y,{className:"text-sm font-medium text-amber-600 dark:text-amber-400 flex items-center gap-2",children:"📝 Archived Features"})}),e.jsxs(N,{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Agent-Days Value Stack"})," - Removed from /dashboard on 2025-01-29. Component saved at ",e.jsx("code",{className:"px-1 py-0.5 rounded bg-muted",children:"src/components/dashboard/AgentDaysValueStack.tsx"})]}),e.jsxs("p",{className:"text-amber-600/70 dark:text-amber-400/70",children:["To re-enable: Import and use ","<AgentDaysValueStack stats={currentStats} />"," in Dashboard.tsx"]})]})]}),e.jsxs(f,{children:[e.jsxs(p,{children:[e.jsx(y,{children:"🧠 Lead Intelligence Tester"}),e.jsx(Q,{children:"Test AI field extraction and custom call context generation"})]}),e.jsxs(N,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Be,{placeholder:"Enter lead phone number or ID",value:a,onChange:n=>s(n.target.value),onKeyDown:n=>n.key==="Enter"&&q()}),e.jsx($,{onClick:q,disabled:c||!a.trim(),children:c?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"mr-2 h-4 w-4 animate-spin"}),"Analyzing..."]}):"Analyze Lead"})]}),k&&e.jsx(Fe,{variant:"destructive",children:e.jsx(Ie,{children:k})})]})]}
25),e.jsx(js,{open:U,onOpenChange:P,leadId:V,results:X,onApplyUpdates:Re,onTestCall:Ve}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs(xe,{value:d,onValueChange:n=>i(n),children:[e.jsx(ue,{className:"w-[180px]",children:e.jsx(he,{placeholder:"Time range"})}),e.jsxs(je,{children:[e.jsx(L,{value:"daily",children:"Daily"}),e.jsx(L,{value:"weekly",children:"Weekly"}),e.jsx(L,{value:"monthly",children:"Monthly"}),e.jsx(L,{value:"quarterly",children:"Quarterly"}),e.jsx(L,{value:"yearly",children:"Yearly"}),e.jsx(L,{value:"all",children:"All Time"})]})]}),e.jsxs(xe,{value:r||"all",onValueChange:n=>m(n==="all"?null:n),children:[e.jsx(ue,{className:"w-[200px]",children:e.jsx(he,{placeholder:"All Organizations"})}),e.jsxs(je,{children:[e.jsx(L,{value:"all",children:"All Organizations"}),l==null?void 0:l.map(n=>e.jsx(L,{value:n.id,children:n.name},n.id))]})]})]}),e.jsxs(ye,{defaultValue:"tokens",className:"space-y-4",children:[e.jsxs(Ne,{children:[e.jsxs(K,{value:"tokens",children:[e.jsx(Ue,{className:"mr-2 h-4 w-4"}),"Token Usage"]}),e.jsxs(K,{value:"overview",children:[e.jsx(Pe,{className:"mr-2 h-4 w-4"}),"Overview"]}),e.jsxs(K,{value:"marketing",children:[e.jsx($e,{className:"mr-2 h-4 w-4"}),"Marketing Gems"]}),e.jsxs(K,{value:"training",children:[e.jsx(ls,{className:"mr-2 h-4 w-4"}),"Training Needs"]}),e.jsxs(K,{value:"showcase",children:[e.jsx(ie,{className:"mr-2 h-4 w-4"}),"AI Showcase"]}),e.jsxs(K,{value:"objections",children:[e.jsx(ve,{className:"mr-2 h-4 w-4"}),"Objections"]}),e.jsxs(K,{value:"failures",children:[e.jsx(ce,{className:"mr-2 h-4 w-4"}),"Failure Modes"]})]}),e.jsx(R,{value:"overview",className:"space-y-4",children:e.jsx(os,{timeRange:d,orgId:r})}),e.jsx(R,{value:"marketing",className:"space-y-4",children:e.jsx(cs,{timeRange:d,orgId:r})}),e.jsx(R,{value:"training",className:"space-y-4",children:e.jsx(ds,{timeRange:d,orgId:r})}),e.jsx(R,{value:"showcase",className:"space-y-4",children:e.jsx(ms,{timeRange:d,orgId:r})}),e.jsx(R,{value:"objections",className:"space-y-4",children:e.jsx(xs,{timeRange:d,orgId:r})}),e.jsx(R,{value:"failures",className:"space-y-4",children:e.jsx(us,{timeRange:d,orgId:r})}),e.jsxs(R,{value:"tokens",className:"space-y-4",children:[e.jsx(ss,{orgId:r}),e.jsx(ts,{orgId:r}),e.jsx(hs,{orgId:r})]})]}),e.jsx(ne,{open:c,onOpenChange:()=>{},children:e.jsx(re,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fe,{className:"bg-accent/50 border-accent",children:e.jsxs(Ie,{className:"text-sm whitespace-pre-wrap text-accent-foreground",children:["✅ DO NOT CLOSE THIS BOX - Tim is processing a complex AI review using TIMTech™️ Patent-Pending Technologies 💡. This typically takes TIM around 3 Minutes to complete.","Don't worry, this is just a test run! 💪"]})}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(oe,{className:"h-6 w-6 animate-spin text-primary flex-shrink-0 mt-1"}),e.jsx("div",{className:"space-y-3 flex-1",children:e.jsx("p",{className:"text-base font-medium whitespace-pre-wrap",children:A})})]})]})})}),e.jsx(ne,{open:se,onOpenChange:()=>{},children:e.jsx(re,{className:"max-w-md",children:e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(oe,{className:"h-8 w-8 animate-spin text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Generating Test Call Context"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"AI is creating custom call context..."})]})]})})})}),e.jsx(ne,{open:!!o,onOpenChange:n=>!n&&B(null),children:e.jsx(re,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Review Test Call Context"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Edit the AI-generated context before scheduling the test call"})]}),o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Schedule Call"}),e.jsxs(xe,{value:o.scheduledMinutes.toString(),onValueChange:n=>B({...o,scheduledMinutes:parseInt(n)}),children:[e.jsx(ue,{children:e.jsx(he,{})}),e.jsxs(je,{children:[e.jsx(L,{value:"1",children:"1 minute from now"}),e.jsx(L,{value:"2",children:"2 minutes from now"}),e.jsx(L,{value:"5",children:"5 minutes from now"}),e.jsx(L,{value:"10",children:"10 minutes from now"}),e.jsx(L,{value:"15",children:"15 minutes from now"}),e.jsx(L,{value:"30",children:"30 minutes from now"}),e.jsx(L,{value:"60",children:"1 hour from now"}),e.jsx(L,{value:"120",children:"2 hours from now"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Action Description"}),e.jsx("textarea",{className:"w-full min-h-[80px] p-3 rounded-md border bg-background resize-none",value:((Se=o.editedContext)==null?void 0:Se.action_description)||"",onChange:n=>B({...o,editedContext:{...o.editedContext,action_description:n.target.value}})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Situational Summary"}),e.jsx("textarea",{className:"w-full min-h-[100px] p-3 rounded-md border bg-background resize-none",value:((Ce=o.editedContext)==null?void 0:Ce.situational_summary)||"",onChange:n=>B({...o,editedContext:{...o.editedContext,situational_summary:n.target.value}})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Key Objectives"}),e.jsx("textarea",{className:"w-full min-h-[100px] p-3 rounded-md border bg-background resize-none",value:((Te=o.editedContext)==null?void 0:Te.key_objectives)||"",onChange:n=>B({...o,editedContext:{...o.editedContext,key_objectives:n.target.value}})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Critical Context"}),e.jsx("textarea",{className:"w-full min-h-[100px] p-3 rounded-md border bg-background resize-none",value:((ke=o.editedContext)==null?void 0:ke.critical_context)||"",onChange:n=>B({...o,editedContext:{...o.editedContext,critical_context:n.target.value}})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Conversation History Summary"}),e.jsx("textarea",{className:"w-full min-h-[100px] p-3 rounded-md border bg-background resize-none",value:((Ae=o.editedContext)==null?void 0:Ae.conversation_history_summary)||"",onChange:n=>B({...o,editedContext:{...o.editedContext,conversation_history_summary:n.target.value}})})]})]}),e.jsxs("div",{className:"flex gap-3 justify-end pt-4 border-t",children:[e.jsx($,{variant:"outline",onClick:()=>B(null),children:"Cancel"}),e.jsx($,{onClick:Ke,disabled:we,children:we?e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"mr-2 h-4 w-4 animate-spin"}),"Scheduling..."]}):`Schedule Test Call (${o.scheduledMinutes>=60?`${o.scheduledMinutes/60}h`:`${o.scheduledMinutes}m`})`})]})]})]})})})]}),e.jsx(Je,{})]})})}export{mt 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.