PageSourceSearch

https://dealerbeast.ai/assets/Leads-1TGayAAC.js

js dealerbeast.ai collected 2026-10-05 15:31:47 UTC 37,728 bytes, 28 lines download raw bytes

1import{j as e}from"./vendor-tanstack-CeuMW_UU.js";import{u as us,q as xs,t as Ds,v as Fs,w as Vs,x as Ms,y as Is,L as F,I as z,z as Us,B as A,s as y,a as ue,E as qe,F as ps,G as $s,b as xe,H as Ps,J as zs,K as He,S as _e,X as Os,R as Rs,l as Ie,N as ls,O as Hs,Q as Ws,V as Xs,W as qs}from"./index-f3p8tUtI.js";import{M as Bs}from"./MobilePullToRefresh-DX2bJ7Vl.js";import{S as V,a as M,b as I,c as U,d as r,C as js}from"./select-Cf745fWX.js";import{u as Qs,L as Gs,a as rs}from"./LeadImportDialog--DHQVWHq.js";import{C as We}from"./checkbox-Be2MRupF.js";import{T as Be,a as Qe,b as q,c as w,d as Ge,e as u}from"./table-CY2Yf63B.js";import{A as Ks,a as Ys}from"./alert-Ch6Whn_a.js";import{r as a,d as Js}from"./vendor-react-DEnzFQ2s.js";import"./featureFlags-DSU7aSn1.js";import{T as Zs}from"./textarea-BTiMUeQ3.js";import{T as et,a as st,b as ns,c as is}from"./tabs-B6he6CMe.js";import{C as gs,a as tt,b as fs}from"./collapsible-DORyVB-c.js";import{U as vs}from"./upload-BmLxZMhD.js";import{e as X,g as at}from"./escapeHtml-CW0NyXRP.js";import{S as lt}from"./SearchableSelect-CTk-Gqyd.js";import{D as rt,a as nt,b as it,c as ct}from"./drawer-DBRLOgk6.js";import{C as cs}from"./circle-alert-CoygYqQa.js";import{D as os}from"./download-ucqdlHw_.js";import{P as ds}from"./printer-CDvXH5pE.js";import{P as ot}from"./plus-D0_6yqjo.js";import{C as dt}from"./chart-column-DaT4S4xH.js";import{S as Xe}from"./search-wPBvxK1v.js";import{C as hs}from"./clock-ffEXti5P.js";import"./vendor-supabase-gM5zGnqC.js";import"./vendor-date-D27i00CA.js";import"./PullToRefresh-bd4b5Z8-.js";import"./index-BO3gyM3-.js";import"./crm-queries-DfduyrOM.js";import"./parseSpreadsheet-BVXVdSes.js";import"./user-plus-Blr2Nw5M.js";import"./file-text-Bd15-eWh.js";import"./index-CAF4JHmU.js";import"./command-DcGFIEtt.js";function ht({open:C,onOpenChange:T,onSuccess:k}){const{toast:_}=us(),{user:f}=xs(),[N,x]=a.useState(!1),[R,d]=a.useState(null),[h,o]=a.useState(null);a.useEffect(()=>{if(!(f!=null&&f.id))return;(async()=>{const{data:b}=await y.from("user_profiles").select("dealership_id").eq("id",f.id).single();if(b!=null&&b.dealership_id)d(b.dealership_id);else{const{data:E}=await y.from("dealerships").select("id").limit(1).single();E&&d(E.id)}const{data:p}=await y.from("salespeople").select("id").eq("user_profile_id",f.id).maybeSingle();p&&o(p.id)})()},[f==null?void 0:f.id]);const[m,j]=a.useState(""),[ie,be]=a.useState(""),[pe,Le]=a.useState(""),[B,ce]=a.useState(""),[Ae,Q]=a.useState(""),[oe,G]=a.useState(""),[je,ge]=a.useState("new"),[fe,$]=a.useState("website"),[ve,Te]=a.useState(""),[se,ke]=a.useState(""),[te,Ne]=a.useState(""),[de,K]=a.useState(""),[ae,Y]=a.useState(""),[le,J]=a.useState(""),Ee=async n=>{if(n.preventDefault(),!R){_({title:"Error",description:"No dealership assigned to your profile. Contact an admin.",variant:"destructive"});return}const b={};oe&&(b.vehicleInterest=oe),ve&&(b.notes=ve),(se||te||de||ae||le)&&(b.creditInfo={...se&&{dateOfBirth:se},...te&&{sin:te},...de&&{employmentStatus:de},...ae&&{monthlyIncome:ae},...le&&{housingStatus:le}});const{data:p,error:E}=await y.from("subscription_leads").insert({first_name:m,middle_name:ie||null,last_name:pe,email:B||null,phone:Ae||null,status:je,lead_source:fe,custom_fields:Object.keys(b).length>0?b:null,user_id:(f==null?void 0:f.id)||null,dealership_id:R,assigned_to:h}).select().single();E?_({title:"Error",description:E.message,variant:"destructive"}):(_({title:"Success",description:"Lead created successfully"}),Z(),T(!1),k==null||k())},Z=()=>{j(""),be(""),Le(""),ce(""),Q(""),G(""),ge("new"),$("website"),Te(""),ke(""),Ne(""),K(""),Y(""),J(""),x(!1)},$e=async n=>{const E=(await n.text()).split(`
2`).slice(1).map(L=>{const[H,ye,re,ne,we,Ce,he]=L.split(","),O=(H==null?void 0:H.trim().split(" "))||[],Fe=O[0]||"",Pe=O.slice(1).join(" ")||"";return{first_name:Fe,last_name:Pe,email:(ye==null?void 0:ye.trim())||null,phone:(re==null?void 0:re.trim())||null,status:(we==null?void 0:we.trim())||"new",lead_source:(Ce==null?void 0:Ce.trim())||"import",user_id:(f==null?void 0:f.id)||null,dealership_id:R,assigned_to:h,custom_fields:{vehicleInterest:(ne==null?void 0:ne.trim())||null,notes:(he==null?void 0:he.trim())||null}}}).filter(L=>L.first_name),{data:De,error:Se}=await y.from("subscription_leads").insert(E).select();if(Se)_({title:"Error",description:Se.message,variant:"destructive"});else{for(const L of De||[])try{await y.functions.invoke("lead-automation",{body:{lead_id:L.id,lead_status:L.status||"new",lead_source:L.lead_source,lead_f
2irst_name:L.first_name,lead_last_name:L.last_name,lead_email:L.email,lead_phone:L.phone,user_id:L.user_id}})}catch(H){console.error("Automation trigger error for lead:",L.id,H)}_({title:"Success",description:`${E.length} leads imported successfully`}),T(!1),k==null||k()}};return e.jsx(Ds,{open:C,onOpenChange:T,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx(Ms,{children:"Add New Lead"}),e.jsx(Is,{children:"Create a new lead manually or import from CSV"})]}),e.jsxs(et,{defaultValue:"manual",className:"w-full",children:[e.jsxs(st,{className:"grid w-full grid-cols-2",children:[e.jsx(ns,{value:"manual",children:"Manual Entry"}),e.jsx(ns,{value:"csv",children:"CSV Upload"})]}),e.jsx(is,{value:"manual",children:e.jsx("form",{onSubmit:Ee,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"First Name"}),e.jsx(z,{value:m,onChange:n=>j(n.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Middle Name"}),e.jsx(z,{value:ie,onChange:n=>be(n.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Last Name"}),e.jsx(z,{value:pe,onChange:n=>Le(n.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Email"}),e.jsx(z,{type:"email",value:B,onChange:n=>ce(n.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Phone"}),e.jsx(z,{value:Ae,onChange:n=>Q(n.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Vehicle Interest"}),e.jsx(z,{value:oe,onChange:n=>G(n.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Status"}),e.jsxs(V,{value:je,onValueChange:ge,children:[e.jsx(M,{children:e.jsx(I,{})}),e.jsxs(U,{children:[e.jsx(r,{value:"new",children:"New"}),e.jsx(r,{value:"hot",children:"Hot"}),e.jsx(r,{value:"warm",children:"Warm"}),e.jsx(r,{value:"cold",children:"Cold"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Source"}),e.jsxs(V,{value:fe,onValueChange:$,children:[e.jsx(M,{children:e.jsx(I,{})}),e.jsxs(U,{children:[e.jsx(r,{value:"website",children:"Website Form"}),e.jsx(r,{value:"database",children:"Database"}),e.jsx(r,{value:"cold-call",children:"Cold Call"}),e.jsx(r,{value:"email-campaign",children:"Email Campaign"}),e.jsx(r,{value:"sms-campaign",children:"SMS Campaign"}),e.jsx(r,{value:"walk-in",children:"Walk-In"}),e.jsx(r,{value:"referral",children:"Referral"}),e.jsx(r,{value:"facebook-ads",children:"Facebook/Meta Ads"}),e.jsx(r,{value:"google-ads",children:"Google Ads"}),e.jsx(r,{value:"canada_drives",children:"Canada Drives"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Notes"}),e.jsx(Zs,{value:ve,onChange:n=>Te(n.target.value)})]}),e.jsxs(gs,{open:N,onOpenChange:x,children:[e.jsxs(tt,{className:"flex items-center justify-between w-full p-3 bg-muted/50 rounded-lg hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Us,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Credit Information (Optional)"})]}),e.jsx(js,{className:`h-4 w-4 transition-transform ${N?"rotate-180":""}`})]}),e.jsxs(fs,{className:"pt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Date of Birth"}),e.jsx(z,{type:"date",value:se,onChange:n=>ke(n.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"SIN (Social Insurance Number)"}),e.jsx(z,{value:te,onChange:n=>Ne(n.target.value),placeholder:"XXX-XXX-XXX",maxLength:11})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Employment Status"}),e.jsxs(V,{value:de,onValueChange:K,children:[e.jsx(M,{children:e.jsx(I,{placeholder:"Select status"})}),e.jsxs(U,{children:[e.jsx(r,{value:"employed",children:"Employed (Full-time)"}),e.jsx(r,{value:"part-time",children:"Employed (Part-time)"}),e.jsx(r,{value:"self-employed",children:"Self-Employed"}),e.jsx(r,{value:"retired",children:"Retired"}),e.jsx(r,{value:"student",children:"Student"}),e.jsx(r,{value:"unemployed",children:"Unemployed"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Monthly Income"}),e.jsx(z,{type:"number",value:ae,onChange:n=>Y(n.target.value),placeholder:"5000",min:"0"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(F,{children:"Housing Status"}),e.jsxs(V,{value:le,onValueChange:J,children:[e.jsx(M,{children:e.jsx(I,{placeholder:"Select status"})}),e.jsxs(U,{children:[e.jsx(r,{value:"own",children:"Own"}),e.jsx(r,{value:"rent",children:"Rent"}),e.jsx(r,{value:"live-with-family",children:"Live with Family"})]})]})]})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(A,{type:"button",variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsx(A,{type:"submit",children:"Save Lead"})]})]})})}),e.jsx(is,{value:"csv",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"border-2 border-dashed border-border rounded-lg p-8 text-center",children:[e.jsx(vs,{className:"w-12 h-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium text-foreground mb-1",children:"Upload CSV File"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"CSV format: Name, Email, Phone, Vehicle, Status, Source, Notes"}),e.jsx(z,{type:"file",accept:".csv",onChange:n=>{var p;const b=(p=n.target.files)==null?void 0:p[0];b&&$e(b)},className:"max-w-xs mx-auto"})]}),e.jsxs("div",{className:"bg-muted p-4 rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"CSV Example:"}),e.jsxs("code",{className:"text-xs",children:["Name,Email,Phone,Vehicle,Status,Source,Notes",e.jsx("br",{}
2),"John Doe,[email protected],(555) 123-4567,2024 Honda Civic,hot,website,Interested in financing"]})]})]})})]})]})})}function ms(C){const T=C/36e5;return T<24?`${Math.round(T)}h`:`${(T/24).toFixed(1)}d`}function mt({leads:C}){const[T,k]=a.useState(!1),[_,f]=a.useState(new Map);a.useEffect(()=>{const d=C.map(o=>o.id);if(d.length===0)return;(async()=>{const{data:o}=await y.from("lead_status_changes").select("lead_id, changed_at").ilike("to_status","%approved%").in("lead_id",d);if(o){const m=new Map;o.forEach(j=>{(!m.has(j.lead_id)||j.changed_at<m.get(j.lead_id))&&m.set(j.lead_id,j.changed_at)}),f(m)}})()},[C]);const N=a.useMemo(()=>{const d=new Map;return C.forEach(h=>{const o=h.lead_source||"Unknown";d.has(o)||d.set(o,{total:0,creditApps:0,approvals:0,delivered:0,closeTimes:[]});const m=d.get(o);m.total++;const j=(h.status||"").toLowerCase();j.includes("credit")&&m.creditApps++,(j.includes("approved")||j.includes("approval"))&&m.approvals++,j.includes("delivered")&&m.delivered++;const ie=_.get(h.id);ie&&h.created_at&&m.closeTimes.push(new Date(ie).getTime()-new Date(h.created_at).getTime())}),Array.from(d.entries()).map(([h,o])=>({source:h,...o,avgCloseTime:o.closeTimes.length>0?o.closeTimes.reduce((m,j)=>m+j,0)/o.closeTimes.length:null})).sort((h,o)=>o.total-h.total)},[C,_]),x=a.useMemo(()=>{const d=N.flatMap(h=>h.closeTimes);return{total:N.reduce((h,o)=>h+o.total,0),creditApps:N.reduce((h,o)=>h+o.creditApps,0),approvals:N.reduce((h,o)=>h+o.approvals,0),delivered:N.reduce((h,o)=>h+o.delivered,0),avgCloseTime:d.length>0?d.reduce((h,o)=>h+o,0)/d.length:null}},[N]);if(C.length===0)return null;const R=(d,h)=>e.jsx("span",{className:d===0?"text-muted-foreground":h||"text-foreground font-medium",children:d});return e.jsx(ue,{className:"mb-6",children:e.jsxs(gs,{open:T,onOpenChange:k,children:[e.jsxs(qe,{className:"pb-3 cursor-pointer flex flex-row items-center justify-between",onClick:()=>k(!T),children:[e.jsx(ps,{className:"text-lg",children:"Lead Source Summary"}),e.jsx(js,{className:$s("h-4 w-4 text-muted-foreground transition-transform",T&&"rotate-180")})]}),e.jsx(fs,{children:e.jsx(xe,{children:e.jsxs(Be,{children:[e.jsx(Qe,{children:e.jsxs(q,{children:[e.jsx(w,{children:"Lead Source"}),e.jsx(w,{className:"text-center",children:"Total"}),e.jsx(w,{className:"text-center",children:"Credit Apps"}),e.jsx(w,{className:"text-center",children:"Approvals"}),e.jsx(w,{className:"text-center",children:"Delivered"}),e.jsx(w,{className:"text-center",children:"Avg Time to Close"})]})}),e.jsxs(Ge,{children:[N.map(d=>e.jsxs(q,{children:[e.jsx(u,{className:"font-medium capitalize",children:d.source.replace(/-/g," ")}),e.jsx(u,{className:"text-center",children:R(d.total)}),e.jsx(u,{className:"text-center",children:R(d.creditApps,"text-info font-medium")}),e.jsx(u,{className:"text-center",children:R(d.approvals,"text-primary font-medium")}),e.jsx(u,{className:"text-center",children:R(d.delivered,"text-success font-medium")}),e.jsx(u,{className:"text-center text-muted-foreground",children:d.avgCloseTime!==null?ms(d.avgCloseTime):"—"})]},d.source)),e.jsxs(q,{className:"border-t-2 font-bold",children:[e.jsx(u,{children:"Total"}),e.jsx(u,{className:"text-center",children:x.total}),e.jsx(u,{className:"text-center text-info",children:x.creditApps}),e.jsx(u,{className:"text-center text-primary",children:x.approvals}),e.jsx(u,{className:"text-center text-success",children:x.delivered}),e.jsx(u,{className:"text-center",children:x.avgCloseTime!==null?ms(x.avgCloseTime):"—"})]})]})]})})})]})})}let Ue=[],Ke=new Map,Ye=[],Je=[];qs(()=>{Ue=[],Ke=new Map,Ye=[],Je=[]});function Bt(){var ts,as;const{toast:C}=us(),T=Js(),{user:k,salespersonId:_,isProfileReady:f}=xs(),{activeRole:N}=Ps(),x=zs(),[R,d]=a.useState(!1),[h,o]=a.useState(!1),[m,j]=a.useState(()=>Ue),[ie,be]=a.useState(Ue.length===0),[pe,Le]=a.useState(new Set),[B,ce]=a.useState(""),Ae=a.useDeferredValue(B),[Q,oe]=a.useState("all"),[G,je]=a.useState("all"),[ge,fe]=a.useState(null),[$,ve]=a.useState(()=>Ke),[Te,se]=a.useState(!1),[ke,te]=a.useState(!1),[Ne,de]=a.useState(new Map),[K,ae]=a.useState("all"),[Y,le]=a.useState("all"),[J,Ee]=a.useState("all"),[Z,$e]=a.useState(()=>Ye),[n,b]=a.useState(()=>Je),[p,E]=a.useState(new Set),De=s=>{E(l=>{const t=new Set(l);return t.has(s)?t.delete(s):t.add(s),t})},Se=()=>{if(v.length===0){C({title:"No data",description:"No leads to print",variant:"destructive"});return}const s=window.open("","_blank");if(!s)return;const l=v.map(t=>`
3      <tr>
4        <td>${X(t.first_name||"")} ${X(t.last_name||"")}</td>
5        <td>${X(t.email||"-")}</td>
6        <td>${X(t.phone||"-")}</td>
7        <td>${X(t.status||"-")}</td>
8        <td>${X(t.lead_source||"-")}</td>
9        <td>${X($.get(t.assigned_to)||"Unassigned")}</td>
10        <td>${X(me(t))}</td>
11        <td>${X(t.created_at?new Date(t.created_at).toLocaleDateString():"-")}</td>
12      </tr>
13    `).join("");s.document.write(`
14      <html><head><title>Leads List</title>
15      <style>
16        body { font-family: Arial, sans-serif; padding: 20px; }
17        h1 { font-size: 18px; margin-bottom: 12px; }
18        table { width: 100%; border-collapse: collapse; font-size: 12px; }
19        th, td { border: 1px solid #ddd; padding: 6px 8px; text-align: left; }
20        th { background: #f5f5f5; font-weight: 600; }
21      </style></head><body>
22      <h1>Leads List (${v.length})</h1>
23      <table>
24        <thead><tr><th>
24Name</th><th>Email</th><th>Phone</th><th>Status</th><th>Source</th><th>Assigned To</th><th>Vehicle Interest</th><th>Created</th></tr></thead>
25        <tbody>${l}</tbody>
26      </table></body></html>
27    `),s.document.close(),s.print()},L=()=>{const s=p.size>0?v.filter(g=>p.has(g.id)):v;if(s.length===0){C({title:"No data",description:"No leads to export",variant:"destructive"});return}const t=[["First Name","Last Name","Email","Phone","Status","Lead Source","Assigned To","Vehicle Interest","Tags","Created At"].join(",")];s.forEach(g=>{const W=Array.isArray(g.tags)?g.tags.join(";"):"",P=[g.first_name||"",g.last_name||"",g.email||"",g.phone||"",g.status||"",g.lead_source||"",$.get(g.assigned_to)||"Unassigned",me(g),W,g.created_at?new Date(g.created_at).toLocaleDateString():""].map(Es=>`"${String(Es).replace(/"/g,'""')}"`);t.push(P.join(","))});const i=t.join(`
28`),c=new Blob([i],{type:"text/csv;charset=utf-8;"}),S=URL.createObjectURL(c),D=document.createElement("a");D.href=S,D.download=`leads-export-${new Date().toISOString().split("T")[0]}.csv`,D.click(),URL.revokeObjectURL(S),C({title:"Exported",description:`${s.length} lead(s) exported to CSV`})};a.useEffect(()=>{m.length>0&&(Ue=m)},[m]),a.useEffect(()=>{$.size>0&&(Ke=$)},[$]),a.useEffect(()=>{Z.length>0&&(Ye=Z)},[Z]),a.useEffect(()=>{n.length>0&&(Je=n)},[n]),a.useEffect(()=>{if(!(!k||!f||!N)){Ns(),Ss(),ys();{be(!1);return}}},[N,f,k==null?void 0:k.id]);const[H,ye]=a.useState("");a.useEffect(()=>{const s=setTimeout(()=>ye(B),300);return()=>clearTimeout(s)},[B]);const[re,ne]=a.useState(0);a.useEffect(()=>{ne(0)},[H,Q,G,K]);const[we,Ce]=a.useState([]),he=N!=="salesperson",O=Qs({search:H,status:Q,source:G,assignedTo:K,page:re},{canViewAll:he,salespersonId:_},{enabled:f&&!!N&&(he||!!_)});a.useEffect(()=>{O.data&&Ce(s=>re===0?O.data.leads:[...s,...O.data.leads])},[O.data,re]),a.useEffect(()=>{const s=m.map(t=>t.id);if(s.length===0)return;(async()=>{const{data:t}=await y.from("lead_status_changes").select("lead_id, changed_at").ilike("to_status","%approved%").in("lead_id",s);if(t){const i=new Map;t.forEach(c=>{(!i.has(c.lead_id)||c.changed_at<i.get(c.lead_id))&&i.set(c.lead_id,c.changed_at)}),de(i)}})()},[m]);const Fe=a.useMemo(()=>{const s=new Map;return m.forEach(l=>{const t=l.lead_source||"Unknown";s.has(t)||s.set(t,{total:0,creditApps:0,approvals:0,delivered:0,closeTimes:[]});const i=s.get(t);i.total++;const c=(l.status||"").toLowerCase();c.includes("credit")&&i.creditApps++,(c.includes("approved")||c.includes("approval"))&&i.approvals++,c.includes("delivered")&&i.delivered++;const S=Ne.get(l.id);S&&l.created_at&&i.closeTimes.push(new Date(S).getTime()-new Date(l.created_at).getTime())}),Array.from(s.entries()).map(([l,t])=>({source:l,...t,avgCloseTime:t.closeTimes.length>0?t.closeTimes.reduce((i,c)=>i+c,0)/t.closeTimes.length:null})).sort((l,t)=>t.total-l.total)},[m,Ne]);function Pe(s){const l=s/36e5;return l<24?`${Math.round(l)}h`:`${(l/24).toFixed(1)}d`}const ze=async(s,l)=>{let i=[],c=0,S=!0,D=null;for(;S;){let g=y.from("subscription_leads").select("*");s&&l&&(g=g.eq("assigned_to",l));const{data:W,error:P}=await g.order("created_at",{ascending:!1}).range(c,c+1e3-1);if(P){D=P;break}i=i.concat(W||[]),S=((W==null?void 0:W.length)||0)===1e3,c+=1e3}return{allLeads:i,lastError:D}},Oe=async()=>{fe(null),console.log("[Leads] Fetching leads...");const s=N==="salesperson";if(s&&!_){j([]);return}const{allLeads:l,lastError:t}=await ze(s,_);if(t){console.error("[Leads] Error fetching leads:",t);const{data:i}=await y.auth.refreshSession();if(i.session){console.log("[Leads] Session refreshed, retrying...");const c=await ze(s,_);if(!c.lastError){console.log("[Leads] Retry fetched",c.allLeads.length,"leads"),j(c.allLeads);return}}fe(t.message),C({title:"Error",description:t.message,variant:"destructive"})}else if(l.length===0){console.log("[Leads] Got 0 leads, attempting session refresh...");const{data:i}=await y.auth.refreshSession();if(i.session){const c=await ze(s,_);if(!c.lastError&&c.allLeads.length>0){console.log("[Leads] After refresh, fetched",c.allLeads.length,"leads"),j(c.allLeads);return}}j([])}else console.log("[Leads] Fetched",l.length,"leads"),j(l)},Ns=async()=>{const{data:s,error:l}=await y.from("subscription_lead_tasks").select("lead_id").eq("status","pen
28ding");!l&&s&&Le(new Set(s.map(t=>t.lead_id)))},Ss=async()=>{const{data:s}=await y.from("salespeople").select("id, name, is_house, user_profile_id");if(s){const l=[...s].sort((t,i)=>t.is_house&&!i.is_house?-1:!t.is_house&&i.is_house?1:(t.name||"").localeCompare(i.name||""));b(l),ve(new Map(s.map(t=>[t.id,t.name])))}},ys=async()=>{if(Z.length>0)return;const{data:s}=await y.from("subscription_pipeline_stages").select("id, stage_name, stage_order").order("stage_order");s&&$e(s)},ws=n.map(s=>({value:s.id,label:s.name})),Cs=async(s,l)=>{var i;const{error:t}=await y.from("subscription_leads").update({assigned_to:l}).eq("id",s);if(t)C({title:"Error",description:t.message,variant:"destructive"});else{C({title:"Assigned",description:`Lead assigned to ${$.get(l)}`}),j(S=>S.map(D=>D.id===s?{...D,assigned_to:l}:D));const c=n.find(S=>S.id===l);if(c&&c.user_profile_id){const S=m.find(P=>P.id===s),D=at(S),{data:{session:g}}=await y.auth.getSession(),W=c.user_profile_id;y.from("notifications").insert({user_id:W,from_user_id:((i=g==null?void 0:g.user)==null?void 0:i.id)||null,type:"lead_assigned",title:`New lead assigned: ${D}`,body:`You have been assigned to ${D}`,resource_type:"lead",resource_id:s}).then(({error:P})=>{P&&console.error("Failed to send assignment notification:",P)}),y.functions.invoke("send-push",{body:{user_id:W,type:"lead_assigned",title:"New lead assigned",body:D,data:{lead_id:s},priority:"normal"}}).then(({error:P})=>{P&&console.error("[push] lead_assigned dispatch failed:",P)})}}},Ze=s=>{switch(s){case"hot":return"bg-destructive/10 text-destructive hover:bg-destructive/20";case"warm":return"bg-warning/10 text-warning hover:bg-warning/20";case"cold":return"bg-info/10 text-info hover:bg-info/20";case"new":return"bg-primary/10 text-primary hover:bg-primary/20";case"converted":return"bg-success/10 text-success hover:bg-success/20";default:return"bg-secondary text-secondary-foreground"}},Ve=s=>`${s.first_name||""} ${s.last_name||""}`.trim()||"Unknown",me=s=>{var l,t;return((l=s.custom_fields)==null?void 0:l.vehicleInterest)||((t=s.custom_fields)==null?void 0:t.vehicle_interest)||"-"},_s=["boat","atv","rv","snowmobile","motorcycle","jet ski","side-by-side","utv","pwc","sled","seadoo","sea-doo","skidoo","ski-doo","pontoon","trailer","camper","motorhome"],bs=["car","truck","suv","sedan","coupe","van","minivan","hatchback","wagon","pickup","crossover","convertible"],Ls=s=>{var i,c;const l=(i=s.custom_fields)==null?void 0:i.vehicleCategory;if(l)return l;const t=(me(s)+" "+(((c=s.custom_fields)==null?void 0:c.vehicleType)||"")).toLowerCase();return _s.some(S=>t.includes(S))?"leisure":bs.some(S=>t.includes(S))?"auto":""},As=s=>{var l,t;return((l=s.custom_fields)==null?void 0:l.newOrUsed)||((t=s.custom_fields)==null?void 0:t.vehicle_type)||""},Re=we,ee=O.isFetching||O.isLoading,Me=((ts=O.data)==null?void 0:ts.total)??0,es=!!((as=O.data)!=null&&as.hasMore),v=Re.filter(s=>{const l=Y==="all"||Ls(s)===Y,t=J==="all"||As(s).toLowerCase()===J;return l&&t}),ss=v.length>0&&v.every(s=>p.has(s.id)),Ts=v.some(s=>p.has(s.id)),ks=()=>{E(ss?new Set:new Set(v.map(s=>s.id)))};return a.useEffect(()=>{E(new Set)},[H,Ae,Q,G,K,Y,J]),!f||!N?e.jsx(He,{children:e.jsxs("div",{className:x?"p-4":"p-8",children:[e.jsxs("div",{className:"mb-8",children:[e.jsx(_e,{className:"h-9 w-32"}),e.jsx(_e,{className:"h-4 w-48 mt-2"})]}),e.jsxs(ue,{children:[e.jsx(qe,{children:e.jsx(_e,{className:"h-5 w-40"})}),e.jsx(xe,{children:e.jsxs(Be,{children:[e.jsx(Qe,{children:e.jsx(q,{children:Array.from({length:8}).map((s,l)=>e.jsx(w,{children:e.jsx(_e,{className:"h-4 w-full"})},l))})}),e.jsx(Ge,{children:Array.from({length:8}).map((s,l)=>e.jsx(q,{children:Array.from({length:8}).map((t,i)=>e.jsx(u,{children:e.jsx(_e,{className:"h-4 w-full"})},i))},l))})]})})]})]})}):N==="salesperson"&&!_?e.jsx(He,{children:e.jsx("div",{className:x?"p-4":"p-8",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(cs,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold text-foreground mb-2",children:"Profile Setup Required"}),e.jsx("p",{className:"text-muted-foreground max-w-md",children:"We couldn't find your salesperson record. Please contact your manager to ensure your profile is properly configured."})]})})}):e.jsx(He,{children:e.jsx(Bs,{children:e.jsxs("div",{className:x?"p-4":"p-8",children:[e.jsx("div",{className:"mb-8",children:e.jsxs("div",{className:x?"flex items-start justify-between":"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:x?"text-2xl font-bold text-foreground":"text-3xl font-bold text-foreground",children:"Leads"}),!x&&e.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage and track all your sales leads"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!x&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(vs,{className:"w-4 h-4 mr-2"}),"Import"]}),e.jsxs(A,{variant:"outline",onClick:L,children:[e.jsx(os,{className:"w-4 h-4 mr-2"}),p.size>0?`Export (${p.size})`:"Export"]}),e.jsxs(A,{variant:"outline",onClick:Se,children:[e.jsx(ds,{className:"w-4 h-4 mr-2"}),"Print"]})]}),x&&e.jsxs(e.Fragment,{children:[e.jsx(A,{variant:"outline",size:"icon",onClick:L,title:p.size>0?`Export ${p.size} selected`:"Export CSV",children:e.jsx(os,{className:"w-4 h-4"})}),e.jsx(A,{variant:"outline",size:"icon",onClick:Se,title:"Print",children:e.jsx(ds,{className:"w-4 h-4"})})]}),e.jsxs(A,{size:x?"sm":"default",className:"gap-2",onClick:()=>d(!0),children:[e.jsx(ot,{className:"w-4 h-4"}),"Add Lead"]})]})]})}),e.jsx(ht,{open:R,onOpenChange:d,onSuccess:Oe}),e.jsx(Gs,{open:h,onOpenChange:o,onImportComplete:Oe}),x?e.jsxs(e.Fragment,{children:[e.jsxs(A,{variant:"outline",className:"w-full mb-4 justify-start gap-2",onClick:()=>te(!0),children:[e.jsx(dt,{className:"w-4 h-4"}),"Lead Source Summary"]}),e.jsx(rt,{open:ke,onOpenChange:te,children:e.jsxs(nt,{className:"max-h-[85vh]",children:[e.jsx(it,{children:e.jsx(ct,{children:"Lead Source Summary"})}),e.jsxs("div",{className:"px-4 pb-6 overflow-y-auto space-y-3",children:[Fe.map(s=>e.jsx(ue,{children:e.jsxs(xe,{className:"p-4 space-y-2",children:[e.jsx("p",{className:"font-semibold capitalize text-foreground",children:s.source.replace(/-/g," ")}),e.jsxs("div",{className:"grid grid-cols-2 gap-y-1 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Total"}),e.jsx("span",{className:"text-right font-medium",children:s.total}),e.jsx("span",{className:"text-muted-foreground",children:"Credit Apps"}),e.jsx("span",{className:"text-right font-medium text-info",children:s.creditApps}),e.jsx("span",{className:"text-muted-foreground",children:"Approvals"}),e.jsx("span",{className:"text-right font-medium text-primary",children:s.approvals}),e.jsx("span",{className:"text-muted-foreground",children:"Delivered"}),e.jsx("span",{className:"text-right font-medium text-success",children:s.delivered}),e.jsx("span",{className:"text-muted-foreground",children:"Avg Close Time"}),e.jsx("span",{className:"text-right text-muted-foreground",children:s.avgCloseTime!==null?Pe(s.avgCloseTime):"—"})]})]})},s.source)),Fe.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No lead data available."})]})]})})]}):e.jsx(mt,{leads:m}),x?e.jsx("div",{className:"mb-4",children:Te?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(Xe,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(z,{placeholder:"Search leads...",className:"pl-9 pr-9 w-full",value:B,onChange:s=>ce(s.target.value),autoFocus:!0}),e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2",onClick:()=>{se(!1),ce("")},children:e.jsx(Os,{className:"w-4 h-4 text-muted-foreground"})})]})}):e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none] pb-1",children:[e.jsx(A,{variant:"outline",size:"icon",className:"shrink-0",onClick:()=>se(!0),children:e.jsx(Xe,{className:"w-4 h-4"})}),e.jsxs(V,{value:Q,onValueChange:oe,children:[e.jsx(M,{className:"w-28 shrink-0",children:e.jsx(I,{placeholder:"Status"})}),e.jsxs(U,{children:[e.jsx(r,{value:"all",children:"All Status"}),Z.map(s=>e.jsx(r,{value:s.stage_name,children:s.stage_name},s.id))]})]}),e.jsxs(V,{value:G,onValueChange:je,children:[e.jsx(M,{className:"w-28 shrink-0",children:e.jsx(I,{placeholder:"Source"})}),e.jsx(U,{children:e.jsx(rs,{})})]}),e.jsxs(V,{value:K,onValueChange:ae,children:[e.jsx(M,{className:"w-32 shrink-0",children:e.jsx(I,{placeholder:"Salesperson"})}),e.jsxs(U,{children:[e.jsx(r,{value:"all",children:"All Reps"}),n.map(s=>e.jsx(r,{value:s.id,children:s.name},s.id))]})]}),e.jsxs(V,{value:Y,onValueChange:le,children:[e.jsx(M,{className:"w-28 shrink-0",children:e.jsx(I,{placeholder:"Category"})}),e.jsxs(U,{children:[e.jsx(r,{value:"all",children:"All Types"}),e.jsx(r,{value:"auto",children:"Auto"}),e.jsx(r,{value:"leisure",children:"Leisure"})]})]}),e.jsxs(V,{value:J,onValueChange:Ee,children:[e.jsx(M,{className:"w-28 shrink-0",children:e.jsx(I,{placeholder:"Condition"})}),e.jsxs(U,{children:[e.jsx(r,{value:"all",children:"All"}),e.jsx(r,{value:"new",children:"New"}),e.jsx(r,{value:"used",children:"Used"}),e.jsx(r,{value:"certified",children:"Certified"})]})]})]})}):e.jsx(ue,{className:"mb-6",children:e.jsx(xe,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(Xe,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(z,{placeholder:"Search leads...",className:"pl-9",value:B,onChange:s=>ce(s.target.value)})]}),e.jsxs(V,{value:Q,onValueChange:oe,children:[e.jsx(M,{className:"w-40",children:e.jsx(I,{placeholder:"Status"})}),e.jsxs(U,{children:[e.jsx(r,{value:"all",children:"All Status"}),Z.map(s=>e.jsx(r,{value:s.stage_name,children:s.stage_name},s.id))]})]}),e.jsxs(V,{value:G,onValueChange:je,children:[e.jsx(M,{className:"w-40",children:e.jsx(I,{placeholder:"Source"})}),e.jsx(U,{children:e.jsx(rs,{})})]}),e.jsxs(V,{value:K,onValueChange:ae,children:[e.jsx(M,{className:"w-44",children:e.jsx(I,{placeholder:"Salesperson"})}),e.jsxs(U,{children:[e.jsx(r,{value:"all",children:"All Salespeople"}),n.map(s=>e.jsx(r,{value:s.id,children:s.name},s.id))]})]}),e.jsxs(V,{value:Y,onValueChange:le,children:[e.jsx(M,{className:"w-36",children:e.jsx(I,{placeholder:"Category"})}),e.jsxs(U,{children:[e.jsx(r,{value:"all",children:"All Categories"}),e.jsx(r,{value:"auto",children:"Auto"}),e.jsx(r,{value:"leisure",children:"Leisure"})]})]}),e.jsxs(V,{value:J,onValueChange:Ee,children:[e.jsx(M,{className:"w-36",children:e.jsx(I,{placeholder:"Condition"})}),e.jsxs(U,{children:[e.jsx(r,{value:"all",children:"All Conditions"}),e.jsx(r,{value:"new",children:"New"}),e.jsx(r,{value:"used",children:"Used"}),e.jsx(r,{value:"certified",children:"Certified Pre-Owned"})]})]})]})})}),ge&&e.jsxs(Ks,{variant:"destructive",className:"mb-6",children:[e.jsx(cs,{className:"h-4 w-4"}),e.jsxs(Ys,{className:"flex items-center justify-between",children:[e.jsxs("span",{children:["Failed to load leads: ",ge]}),e.jsxs(A,{variant:"outline",size:"sm",onClick:Oe,className:"ml-4",children:[e.jsx(Rs,{className:"w-4 h-4 mr-2"}),"Retry"]})]})]}),x?e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:ee&&v.length===0?"Loading...":`Showing ${v.length} of ${Me} leads`}),p.size>0&&e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsxs("span",{className:"font-medium",children:[p.size," selected"]}),e.jsx(A,{variant:"ghost",size:"sm",className:"h-7 px-2 text-muted-foreground",onClick:()=>E(new Set),children:"Clear"})]}),ee&&v.length===0?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ie,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):v.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:Re.length===0?"N
28o leads found.":"No leads match your search criteria."}):v.map(s=>e.jsx(ue,{className:"cursor-pointer active:scale-[0.98] transition-transform",onClick:()=>T(`/leads/${s.id}`),children:e.jsxs(xe,{className:"p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{onClick:l=>l.stopPropagation(),className:"flex items-center",children:e.jsx(We,{checked:p.has(s.id),onCheckedChange:()=>De(s.id),"aria-label":`Select ${Ve(s)}`})}),e.jsx("span",{className:"font-semibold text-foreground",children:Ve(s)}),pe.has(s.id)&&e.jsx(hs,{className:"w-4 h-4 text-primary"})]}),e.jsx(ls,{className:Ze(s.status||"new"),children:s.status||"new"})]}),e.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-sm",children:[(s.email||s.phone)&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"Contact"}),e.jsx("span",{className:"truncate",children:s.email||s.phone})]}),me(s)!=="-"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"Vehicle"}),e.jsx("span",{className:"truncate",children:me(s)})]}),e.jsx("span",{className:"text-muted-foreground",children:"Source"}),e.jsx("span",{children:s.lead_source||"-"}),e.jsx("span",{className:"text-muted-foreground",children:"Assigned"}),e.jsx("span",{children:$.get(s.assigned_to)||"Unassigned"}),e.jsx("span",{className:"text-muted-foreground",children:"Updated"}),e.jsx("span",{className:"text-muted-foreground",children:s.updated_at||s.created_at?new Date(s.updated_at||s.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"}):"-"})]})]})},s.id)),es&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(A,{variant:"outline",onClick:()=>ne(s=>s+1),disabled:ee,className:"w-full",children:ee?e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-4 h-4 mr-2 animate-spin"}),"Loading..."]}):e.jsxs(e.Fragment,{children:["Load more (",Me-v.length," remaining)"]})})})]}):e.jsxs(ue,{children:[e.jsx(qe,{children:e.jsxs(ps,{children:["All Leads",!ee&&` (showing ${v.length} of ${Me})`]})}),e.jsxs(xe,{children:[p.size>0&&e.jsxs("div",{className:"flex items-center gap-3 mb-3 text-sm",children:[e.jsxs("span",{className:"font-medium",children:[p.size," selected"]}),e.jsx(A,{variant:"ghost",size:"sm",className:"h-7 px-2 text-muted-foreground",onClick:()=>E(new Set),children:"Clear"})]}),e.jsxs(Be,{children:[e.jsx(Qe,{children:e.jsxs(q,{children:[e.jsx(w,{className:"w-[40px]",children:e.jsx(We,{checked:ss?!0:Ts?"indeterminate":!1,onCheckedChange:ks,"aria-label":"Select all leads"})}),e.jsx(w,{className:"w-[12%]",children:"Name"}),e.jsx(w,{className:"w-[15%]",children:"Contact"}),e.jsx(w,{className:"w-[15%]",children:"Vehicle Interest"}),e.jsx(w,{className:"w-[12%]",children:"Assigned To"}),e.jsx(w,{children:"Status"}),e.jsx(w,{children:"Source"}),e.jsx(w,{children:"Last Updated"}),e.jsx(w,{children:"Created"}),e.jsx(w,{className:"text-right",children:"Actions"})]})}),e.jsx(Ge,{children:ee&&v.length===0?e.jsx(q,{children:e.jsx(u,{colSpan:10,className:"text-center py-12",children:e.jsx(Ie,{className:"w-6 h-6 animate-spin text-muted-foreground mx-auto"})})}):v.length===0?e.jsx(q,{children:e.jsx(u,{colSpan:10,className:"text-center text-muted-foreground py-8",children:Re.length===0?"No leads found.":"No leads match your search criteria."})}):v.map(s=>e.jsxs(q,{"data-state":p.has(s.id)?"selected":void 0,children:[e.jsx(u,{children:e.jsx(We,{checked:p.has(s.id),onCheckedChange:()=>De(s.id),"aria-label":`Select ${Ve(s)}`})}),e.jsx(u,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Ve(s),pe.has(s.id)&&e.jsxs(Hs,{children:[e.jsx(Ws,{children:e.jsx(hs,{className:"w-4 h-4 text-primary"})}),e.jsx(Xs,{children:e.jsx("p",{children:"Task scheduled"})})]})]})}),e.jsx(u,{children:e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{children:s.email||"-"}),e.jsx("div",{className:"text-muted-foreground",children:s.phone||"-"})]})}),e.jsx(u,{children:me(s)}),e.jsx(u,{className:"text-sm text-muted-foreground",children:s.assigned_to&&$.get(s.assigned_to)?$.get(s.assigned_to):N==="salesperson"?e.jsx("span",{className:"text-muted-foreground",children:"Unassigned"}):e.jsx(lt,{options:ws,value:"",onValueChange:l=>Cs(s.id,l),placeholder:"Assign...",searchPlaceholder:"Search salespeople...",emptyMessage:"No salespeople found."})}),e.jsx(u,{children:e.jsx(ls,{className:Ze(s.status||"new"),children:s.status||"new"})}),e.jsx(u,{children:s.lead_source||"-"}),e.jsx(u,{className:"text-muted-foreground text-sm",children:s.updated_at||s.created_at?new Date(s.updated_at||s.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"-"}),e.jsx(u,{className:"text-muted-foreground text-sm",children:new Date(s.created_at).toLocaleDateString()}),e.jsx(u,{className:"text-right",children:e.jsx(A,{variant:"ghost",size:"sm",onClick:()=>T(`/leads/${s.id}`),children:"View"})})]},s.id))})]}),es&&e.jsx("div",{className:"flex justify-center pt-4",children:e.jsx(A,{variant:"outline",onClick:()=>ne(s=>s+1),disabled:ee,children:ee?e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-4 h-4 mr-2 animate-spin"}),"Loading..."]}):e.jsxs(e.Fragment,{children:["Load more (",Me-v.length," remaining)"]})})})]})]})]})})})}export{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.