1import{r as o,j as e,h as Zs}from"./vendor-react-BZE6wSbZ.js";import{I as Xs}from"./ImportFromQuickBooksButton-eVcf39FZ.js";import{u as Me,f as Ge,g as fe,k as Is,B as k,c as Y,i as xs,X as De,L as de,s as K,h as Ps,l as D,q as Je,T as Ue,a as He,b as Ve,d as Ke}from"./index-BHxCMQCy.js";import{u as Ws}from"./useCommercialAccount-NXkT_DFt.js";import{u as Gs,O as et,M as st}from"./RentalHistoryPage-CyK3dQFn.js";import{u as tt,f as ps,d as hs}from"./useCompanyTimezone-BcFs_CUl.js";import{C as rt}from"./CustomerCreateModal-CijgNUHX.js";import{D as Le,a as $e,b as Oe,c as qe,d as Re,e as at}from"./dialog-C0WElyCa.js";import{S as nt}from"./scroll-area-DN_K-A3u.js";import{B as ee}from"./badge-D48-Z7tR.js";import{S as ye}from"./separator-Cn0AhSti.js";import{n as Ts}from"./formatAddress-CrGxQ0C7.js";import{F as it}from"./file-spreadsheet-C7ONrlkg.js";import{D as ot}from"./download-CN0omQZF.js";import{U as Ye}from"./upload-CzxAod4Y.js";import{C as Fe}from"./circle-check-CxOyNTB_.js";import{T as Ds}from"./trash-2-BtdyQuxL.js";import{A as lt,C as ct}from"./AcceptedEstimatesBanner-Cv_HKnLF.js";import{I as es}from"./input-CPRcq4Mq.js";import{C as Ae}from"./checkbox-DJeO7ukx.js";import{T as dt,a as mt,b as Ce,c as ce,d as ut,e as G}from"./table-C3xOo3Ar.js";import{S as fs,a as gs,b as js,c as vs,d as xe}from"./select-DlZm8Hd1.js";import{T as xt}from"./TablePagination-BLXKxcGv.js";import{u as Ne}from"./useLocaleFormat-D7hA3WYI.js";import{u as he}from"./useMutation-CMZdJJWH.js";import{I as pt}from"./inbox-DVtkHB_w.js";import{C as ht}from"./chevron-up-Gpuo3T0-.js";import{C as Fs}from"./chevron-down-CvE1o0oO.js";import{S as As}from"./sparkles-BlnI9b2K.js";import{P as ft}from"./phone-call-Y1oU6QPm.js";import{U as gt}from"./user-plus-C4XUCNf5.js";import{u as jt}from"./useBookingConfig-bZ4z8ARb.js";import{b as Ee}from"./publicUrl-CPxq3Pwk.js";import{c as Es}from"./clipboard-B8jfV5Lw.js";import{L as Ze}from"./label-BdVoReUu.js";import{S as Te}from"./switch-C3e2eCWO.js";import{i as vt}from"./useCompanyCurrency-DsQ7Wf_J.js";import{extractEdgeError as Se}from"./edgeError-C-0OAb9E.js";import{L as ie}from"./layers-CbKTMb1v.js";import{S as ss}from"./send-7DQkxcDv.js";import{C as Xe}from"./copy-Cm1Bi4XC.js";import{E as zs}from"./external-link-DB-Us676.js";import{C as ze}from"./credit-card-C5D54qC9.js";import{F as Ms}from"./file-text-n3Ul6Zql.js";import{A as bt,h as yt,a as Nt,b as wt,c as _t,d as Ct,e as St,f as kt,g as It}from"./alert-dialog-X5-H8hGj.js";import{M as Pt}from"./mail-Do8Gu7xQ.js";import{M as Tt}from"./message-square-eCaNqSY7.js";import{S as bs}from"./shield-alert-DhVByXlf.js";import{C as We}from"./chevron-right-DaK95j4Q.js";import{P as Ls}from"./plus-BmY2DLoW.js";import{B as Dt}from"./ban-R9GaIRq3.js";import{U as ys}from"./users-DUTtq8w-.js";import{S as Ft}from"./shopping-cart-CmdjQyyX.js";import{D as At}from"./dollar-sign-DVj2tR7B.js";import{H as Qe}from"./hard-hat-Bw8IRMzd.js";import{S as Et}from"./search-CQ2EdEXt.js";import{H as Ns}from"./house-BeU32h02.js";import{B as ws}from"./building-2-BxSGiiio.js";import{B as _s}from"./briefcase-Oi032ixv.js";import{L as Cs}from"./list-ordered-DnP9u_MJ.js";import{A as zt}from"./arrow-up-down-mzdPeQIr.js";import"./vendor-shared-BX-e1btJ.js";import"./QuickBooksTab-BL7nirgq.js";import"./card-B3eKkm-G.js";import"./useScrapMetalUi-T7fF2oOL.js";import"./useBusinessLines-DRKDW3Og.js";import"./scrapMetalFlags-B8JB2ufG.js";import"./link-2-lwpvhxdq.js";import"./unlink-C5Kc_MGz.js";import"./info-Cs_OlzJ-.js";import"./collapsible-GfsuY8RP.js";import"./index-BJ99mubw.js";import"./stampPhoto-DSehgX-8.js";import"./googleMapsLoader-BDrLlvC1.js";import"./storagePhotoRef-RPQ-_QZD.js";import"./useCompanyName-CKQr2rco.js";import"./camera-CZyd59eF.js";import"./eye-BSedJ_Lb.js";import"./image-D3njFq4q.js";import"./PhotoLightbox-C7aGc1Ct.js";import"./index-CHWkcEiC.js";import"./zoom-out-otyF_KSL.js";import"./chevron-left-CzNb9mqx.js";import"./popover-BILSYO6d.js";import"./index-jOKYf_8M.js";import"./calendar-8dstdXYM.js";import"./format-Ak5kxEOW.js";import"./en-US-CDCURxqZ.js";import"./isBefore-DXvilnu8.js";import"./endOfMonth-MLffDwdQ.js";import"./startOfMonth-DPgKP1OF.js";import"./dropdown-menu-CifQfXna.js";import"./index-C39pvbTH.js";import"./index-BwGl0rKo.js";import"./check-Dk7x8bFW.js";import"./circle-AJ9Cij-i.js";import"./textarea-msR5xLHq.js";import"./reconciliation-DOlR0lV9.js";import"./replace-Nl2AmFTL.js";import"./costClassification-8wUBdUoj.js";
1import"./target-CrQ6EkQW.js";import"./vendor-charts-BpCwEk9S.js";import"./alert-D5q1pBOx.js";import"./refund-fees-lWDaf_Hl.js";import"./ChargeExtraModal-B4CgtYeX.js";import"./pencil-urSf7tfe.js";import"./useCompanyStripeStatus-BQMVXa6N.js";import"./StripeNudge-DD0r_a99.js";import"./MoneyInput-D6QvUOJy.js";import"./LandfillReceiptVisibilityToggle-B913FYJW.js";import"./eye-off-CnkBK3yR.js";import"./scrapOrderGate-CZSTBsGR.js";import"./weight-ZOqxHHjP.js";import"./calculator-BuMRe_IQ.js";import"./tag-BKYtSSpI.js";import"./percent-C8D7Xo3P.js";import"./expand-CI-2OU0c.js";import"./shield-D26o9Zv9.js";import"./file-warning-YCYXaen_.js";import"./circle-x-ECH2vLdE.js";import"./hammer-CdwxbLVK.js";import"./truck-CVTcUvvC.js";import"./useSignedPhoto-AqVMYxzZ.js";import"./tabs-BHQ5Yymq.js";import"./pencil-line-D98sCgsB.js";import"./circle-alert-B0NtQulp.js";import"./RentalExtensionRequestBlock-WQF6Z0ZS.js";import"./crown-DIeN_tOo.js";import"./arrow-right-BFutNm6y.js";import"./banknote-Ds47EwUN.js";import"./calendar-clock-JVNs_Ihd.js";import"./calendar-plus-BA3mTfN3.js";import"./useOverweightPending-t2yX0oja.js";import"./receipt-Bi37N1a1.js";import"./star-D2TIeRtk.js";import"./vendor-pdf-B7_0ag-b.js";import"./useReleaseAuthorization-CHOMAat1.js";import"./lock-open-Dg1_7-gp.js";import"./phone-BB1Uu4MG.js";import"./rotate-ccw-CnuMuHYe.js";import"./clock-DVpcraFk.js";import"./user-BwsKHJRy.js";import"./undo-2-CdHhVQdy.js";import"./AddressAutocompleteInput-YVVKgwsN.js";import"./useGooglePlacesAutocomplete-B38ueeNh.js";import"./save-DwrVIBox.js";import"./clipboard-list-BzD0XU4v.js";import"./package-DgdJYsJT.js";import"./package-open-D3hm1s5V.js";import"./recycle-GoWGl8gD.js";import"./printer-9I8AeYiY.js";import"./trending-up-DeLBbODI.js";import"./calendar-days-BBNxAWQc.js";import"./hand-coins-ku2oWXsH.js";import"./zap-B7SnO8Ln.js";import"./ellipsis-Bjo2YENC.js";import"./index-CsEg0OB-.js";import"./index-BdQq_4o_.js";import"./lock-DhkjFvsf.js";import"./formatUsPhone-BV-153F8.js";import"./useAcceptedEstimates-dMNiX9Id.js";import"./index-D3Zdq0oI.js";const Mt=["first_name","last_name","email","phone","customer_type","company_name","address_line1","city","state","zip_code","notes"],Ss=["residential","contractor","broker"];function Lt(){return`${Mt.join(",")} 2John,Doe,[email protected],(555) 123-4567,residential,,123 Main St,Miami,FL,33101,New customer 3Jane,Smith,[email protected],(555) 987-6543,contractor,Smith Construction,456 Oak Ave,Orlando,FL,32801,`}function $t(){const r=Lt(),a=new Blob([r],{type:"text/csv;charset=utf-8;"}),s=URL.createObjectURL(a),l=document.createElement("a");l.href=s,l.download="customer_import_template.csv",l.click(),URL.revokeObjectURL(s)}function Ot(r){return r.split(/\r?\n/).filter(s=>s.trim().length>0).map(s=>{const l=[];let h="",c=!1;for(let w=0;w<s.length;w++){const p=s[w];p==='"'?c&&s[w+1]==='"'?(h+='"',w++):c=!c:p===","&&!c?(l.push(h.trim()),h=""):h+=p}return l.push(h.trim()),l})}function qt(r){return r?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r):!0}function Rt(r,a,s){const l={};a.forEach((c,w)=>{const p=c.toLowerCase().replace(/\s+/g,"_").trim();l[p]=w});const h=(c,w)=>{const p=l[w];return p!==void 0&&p<c.length?c[p].trim():""};return r.map((c,w)=>{const p=[],j=[],v=h(c,"first_name"),_=h(c,"last_name"),g=h(c,"email"),i=h(c,"phone"),b=h(c,"customer_type").toLowerCase(),P=h(c,"company_name"),m=Ts({line1:h(c,"address_line1"),city:h(c,"city"),state:h(c,"state"),zip:h(c,"zip_code")}),I=m.street,U=m.city,f=m.state,A=m.zip,te=h(c,"notes");return v||p.push(s("customers.firstNameRequired")),g&&!qt(g)&&p.push(s("customers.invalidEmailFormat")),b&&!Ss.includes(b)&&j.push(s("customers.unknownTypeDefault",{type:b})),_||j.push(s("customers.lastNameEmpty")),g||j.push(s("customers.emailEmpty")),i||j.push(s("customers.phoneEmpty")),{row:w+2,first_name:v,last_name:_||"",email:g.toLowerCase(),phone:i,customer_type:Ss.includes(b)?b:"residential",company_name:P,address_line1:I,city:U,state:f,zip_code:A,notes:te,errors:p,warnings:j}})}function Bt({open:r,onClose:a}){const{t:s}=Me(),{user:l}=Ge(),h=fe(),{toast:c}=Is(),w=o.useRef(null),[p,j]=o.useState("upload"),[v,_]=o.useState(""),[g,i]=o.useState([]),[b,P]=o.useState({success:0,failed:0,duplicates:0}
3),[m,I]=o.useState(!1),U=()=>{j("upload"),_(""),i([]),P({success:0,failed:0,duplicates:0}),I(!1),w.current&&(w.current.value="")},f=()=>{U(),a()},A=o.useCallback(u=>{if(!u.name.endsWith(".csv")){c({title:s("customers.invalidFile"),description:s("customers.pleaseUploadCsv"),variant:"destructive"});return}_(u.name);const $=new FileReader;$.onload=z=>{var N;const H=(N=z.target)==null?void 0:N.result,O=Ot(H);if(O.length<2){c({title:s("customers.emptyFile"),description:s("customers.noDataRows"),variant:"destructive"});return}const V=O[0],C=O.slice(1),y=Rt(C,V,s);i(y),j("review")},$.readAsText(u)},[c,s]),te=o.useCallback(u=>{u.preventDefault();const $=u.dataTransfer.files[0];$&&A($)},[A]),n=async()=>{if(!(l!=null&&l.companyId))return;j("importing"),I(!0);const u=g.filter(N=>N.errors.length===0);let $=0,z=0,H=0;const{data:O}=await K.from("customers").select("email").eq("company_id",l.companyId).is("deleted_at",null),V=new Set((O||[]).map(N=>{var X;return(X=N.email)==null?void 0:X.toLowerCase()}).filter(Boolean)),C=20;for(let N=0;N<u.length;N+=C){const X=u.slice(N,N+C),se=[];for(const T of X){if(T.email&&V.has(T.email)){H++;continue}se.push({company_id:l.companyId,first_name:T.first_name,last_name:T.last_name,email:T.email||null,phone:T.phone||null,customer_type:T.customer_type,company_name:T.company_name||null,address_line1:T.address_line1||null,city:T.city||null,state:T.state||null,zip_code:T.zip_code||null,notes:T.notes||null}),T.email&&V.add(T.email)}if(se.length>0){const{data:T,error:oe}=await K.from("customers").insert(se).select("id");oe?(z+=se.length,console.error("[CustomerImport] Batch insert error:",oe)):$+=T.length}}const y=g.filter(N=>N.errors.length>0).length;z+=y,P({success:$,failed:z,duplicates:H}),j("done"),I(!1),h.invalidateQueries({queryKey:["customers-list"]})},L=g.filter(u=>u.errors.length>0).length,J=g.filter(u=>u.warnings.length>0&&u.errors.length===0).length,Z=g.filter(u=>u.errors.length===0).length;return e.jsx(Le,{open:r,onOpenChange:u=>!u&&f(),children:e.jsxs($e,{className:"sm:max-w-lg max-h-[90vh] flex flex-col gap-0 p-0",children:[e.jsxs(Oe,{className:"px-5 pt-5 pb-3",children:[e.jsx(qe,{className:"text-lg font-semibold",children:s(p==="done"?"customers.importComplete":"customers.importCustomers")}),e.jsxs(Re,{className:"text-sm text-muted-foreground",children:[p==="upload"&&s("customers.uploadCsvDesc"),p==="review"&&s("customers.rowsFound",{count:g.length}),p==="importing"&&s("customers.importingCustomers"),p==="done"&&s("customers.customersImported")]})]}),e.jsx(ye,{}),e.jsxs("div",{className:"flex-1 overflow-hidden",children:[p==="upload"&&e.jsxs("div",{className:"p-5 space-y-5",children:[e.jsx("div",{className:"rounded-xl border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(it,{className:"w-4.5 h-4.5 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:s("customers.downloadTemplate")}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:s("customers.downloadTemplateDesc")}),e.jsxs(k,{variant:"outline",size:"sm",className:"mt-2.5 h-8 text-xs gap-1.5 rounded-lg",onClick:$t,children:[e.jsx(ot,{className:"w-3.5 h-3.5"})," ",s("customers.downloadCsvTemplate")]})]})]})}),e.jsxs("div",{className:Y("relative border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-colors","border-border hover:border-primary/40 hover:bg-primary/5",v&&"border-primary/30 bg-primary/5"),onDragOver:u=>u.preventDefault(),onDrop:te,onClick:()=>{var u;return(u=w.current)==null?void 0:u.click()},children:[e.jsx("input",{ref:w,type:"file",accept:".csv",className:"hidden",onChange:u=>{var z;const $=(z=u.target.files)==null?void 0:z[0];$&&A($)}}),e.jsx(Ye,{className:"w-8 h-8 text-muted-foreground/50 mx-auto"}),e.jsx("p",{className:"text-sm font-medium text-foreground mt-3",children:s("customers.dropCsvHere")}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:s("customers.onlyCsvSupported")})]})]}),p==="review"&&e.jsxs("div",{className:"flex flex-col",style:{maxHeight:"calc(90vh - 200px)"},children:[e.jsxs("div",{className:"px-5 py-3 flex flex-wrap items-center gap-2",children:[e.jsxs(ee,{variant:"outline",className:"gap-1 text-xs bg-emerald-50 text-emerald-700 border-emerald-200",children:[e.jsx(Fe,{className:"w-3 h-3"})," ",Z," ",s("customers.valid")]}),J>0&&e.jsxs(ee,{variant:"outline",className:"gap-1 text-xs bg-amber-50 text-amber-700 border-amber-200",children:[e.jsx(xs,{className:"w-3 h-3"})," ",J," ",s("customers.warnings")]}),L>0&&e.jsxs(ee,{variant:"outline",className:"gap-1 text-xs bg-destructive/10 text-destructive border-destructive/20",children:[e.jsx(De,{className:"w-3 h-3"})," ",L," ",s("customers.errors")]}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:v})]}),e.jsx(ye,{}),e.jsx(nt,{className:"flex-1 px-5 py-3",style:{maxHeight:"350px"},children:e.jsx("div",{className:"space-y-2",children:g.map((u,$)=>e.jsxs("div",{className:Y("rounded-lg border p-3 text-xs",u.errors.length>0?"border-destructive/30 bg-destructive/5":u.warnings.length>0?"border-amber-200 bg-amber-50/50":"border-border bg-card"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsxs("span",{className:"text-muted-foreground font-mono w-6 shrink-0",children:["#",u.row]}),e.jsxs("span",{className:"font-medium text-foreground truncate",children:[u.first_name," ",u.last_name]}),u.email&&e.jsx("span",{className:"text-muted-foreground truncate hidden sm:inline",children:u.email})]}),e.jsx(ee,{variant:"outline",className:"text-[10px] shrink-0 capitalize",children:u.customer_type})]}),u.errors.length>0&&e.jsx("div",{className:"mt-1.5 space-y-0.5",children:u.errors.map((z,H)=>e.jsxs("p",{className:"text-destructive flex items-center gap-1",children:[e.jsx(De,{className:"w-3 h-3 shrink-0"})," ",z]},H))}),u.warnings.length>0&&u.errors.length===0&&e.jsx("div",{className:"mt-1.5 space-y-0.5",children:u.warnings.map((z,H)=>e.jsxs("p",{className:"text-amber-600 flex items-center gap-1",children:[e.jsx(xs,{className:"w-3 h-3 shrink-0"})," ",z]},H))})]},$))})})]}),p==="importing"&&e.jsxs("div",{className:"p-10 flex flex-col items-center justify-center gap-4",children:[e.jsx(de,{className:"w-10 h-10 text-primary animate-spin"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:s("customers.importingCustomersD
3ots")}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:s("customers.thisMayTakeMoment")})]})]}),p==="done"&&e.jsxs("div",{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-col items-center text-center gap-3 py-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-emerald-100 flex items-center justify-center",children:e.jsx(Fe,{className:"w-6 h-6 text-emerald-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-base font-semibold text-foreground",children:s("customers.importComplete")}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s("customers.importCompleteDesc")})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4 text-center",children:[e.jsx("p",{className:"text-2xl font-semibold text-emerald-600",children:b.success}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:s("customers.imported")})]}),e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4 text-center",children:[e.jsx("p",{className:"text-2xl font-semibold text-amber-600",children:b.duplicates}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:s("customers.duplicates")})]}),e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4 text-center",children:[e.jsx("p",{className:"text-2xl font-semibold text-destructive",children:b.failed}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:s("customers.failed")})]})]})]})]}),e.jsx(ye,{}),e.jsxs("div",{className:"px-5 py-3 flex items-center justify-between gap-2",children:[p==="upload"&&e.jsx(k,{variant:"ghost",size:"sm",className:"h-9 text-sm",onClick:f,children:s("customers.cancel")}),p==="review"&&e.jsxs(e.Fragment,{children:[e.jsxs(k,{variant:"ghost",size:"sm",className:"h-9 text-sm gap-1.5",onClick:U,children:[e.jsx(Ds,{className:"w-3.5 h-3.5"})," ",s("customers.startOver")]}),e.jsxs(k,{size:"sm",className:"h-9 text-sm gap-1.5",onClick:n,disabled:Z===0,children:[e.jsx(Ye,{className:"w-3.5 h-3.5"}),Z!==1?s("customers.importCountPlural",{count:Z}):s("customers.importCount",{count:Z})]})]}),p==="done"&&e.jsx(k,{size:"sm",className:"h-9 text-sm ml-auto",onClick:f,children:s("customers.done")})]})]})})}function Ut({defaultExpanded:r=!1}){const{t:a}=Me(),{user:s}=Ge(),{formatDate:l}=Ne(),h=fe(),[c,w]=o.useState(r),{data:p=[],isLoading:j}=Ps({queryKey:["company-leads",s==null?void 0:s.companyId],enabled:!!(s!=null&&s.companyId),queryFn:async()=>{const{data:i,error:b}=await K.from("leads").select("id, name, phone, email, address, size_label, note, status, source, created_at").eq("company_id",s.companyId).neq("status","discarded").order("created_at",{ascending:!1}).limit(50);if(b)throw b;return i??[]}}),v=he({mutationFn:async({id:i,status:b,convertedCustomerId:P})=>{const{data:m,error:I}=await K.from("leads").update({status:b,updated_at:new Date().toISOString(),...P?{converted_customer_id:P}:{}}).eq("id",i).eq("company_id",s.companyId).select("id");if(I)throw I;if(!m||m.length===0)throw new Error("lead_update_blocked")},onSuccess:()=>{h.invalidateQueries({queryKey:["company-leads"]})},onError:()=>D.error(a("leadsPanel.updateFail"))}),_=he({mutationFn:async i=>{const b=i.name.trim().split(/\s+/),P=b[0]??i.name,m=b.slice(1).join(" ")||"-",I=Ts({line1:i.address}),{data:U,error:f}=await K.from("customers").insert({company_id:s.companyId,first_name:P,last_name:m,email:i.email,phone:i.phone,address_line1:I.street||i.address,city:I.city||null,state:I.state||null,zip_code:I.zip||null,customer_type:"residential",notes:i.note?`Lead (API): ${i.note}`:"Converted from API lead"}).select("id").single();if(f)throw f;const A=U.id;return await v.mutateAsync({id:i.id,status:"converted",convertedCustomerId:A}),A},onSuccess:()=>{D.success(a("leadsPanel.converted")),h.invalidateQueries({queryKey:["customers"]})},onError:()=>D.error(a("leadsPanel.convertFail"))}),g=p.filter(i=>i.status==="new").length;return!j&&p.length===0?null:e.jsxs("div",{className:"rounded-xl border border-border bg-card overflow-hidden",children:[e.jsxs("button",{onClick:()=>w(i=>!i),className:"w-full flex items-center gap-2.5 px-4 py-3 text-left hover:bg-muted/40 transition-colors",children:[e.jsx("span",{className:"w-8 h-8 rounded-lg bg-cyan-500/10 flex items-center justify-center shrink-0",children:e.jsx(pt,{className:"w-4 h-4 text-cyan-600"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-semibold text-foreground flex items-center gap-2",children:[a("leadsPanel.title"),g>0&&e.jsx(ee,{className:"text-[10px] h-5 bg-cyan-600 hover:bg-cyan-600",children:a("leadsPanel.newCount",{count:g})})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a("leadsPanel.subtitle")})]}),c?e.jsx(ht,{className:"w-4 h-4 text-muted-foreground"}):e.jsx(Fs,{className:"w-4 h-4 text-muted-foreground"})]}),c&&e.jsx("div",{className:"border-t border-border divide-y divide-border",children:p.map(i=>e.jsxs("div",{className:"px-4 py-3 flex flex-col sm:flex-row sm:items-center gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium text-foreground flex items-center gap-2",children:[i.name,i.status==="new"&&e.jsx(As,{className:"w-3.5 h-3.5 text-cyan-500"}),i.status==="contacted"&&e.jsx(ee,{variant:"outline",className:"text-[10px]",children:a("leadsPanel.statusContacted")}),i.status==="converted"&&e.jsx(ee,{variant:"outline",className:"text-[10px] text-emerald-600 border-emerald-500/40",children:a("leadsPanel.statusConverted")})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:[i.phone,i.email,i.size_label].filter(
3Boolean).join(" · ")}),i.address&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:i.address}),i.note&&e.jsx("p",{className:"text-xs text-muted-foreground/80 truncate",children:i.note}),e.jsxs("p",{className:"text-[11px] text-muted-foreground/70",children:[l(i.created_at)," · ",i.source]})]}),i.status!=="converted"&&e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[i.status==="new"&&e.jsxs(k,{variant:"outline",size:"sm",className:"h-8 gap-1 text-xs",disabled:v.isPending,onClick:()=>v.mutate({id:i.id,status:"contacted"}),children:[e.jsx(ft,{className:"w-3.5 h-3.5"})," ",a("leadsPanel.markContacted")]}),e.jsxs(k,{size:"sm",className:"h-8 gap-1 text-xs",disabled:_.isPending,onClick:()=>_.mutate(i),children:[e.jsx(gt,{className:"w-3.5 h-3.5"})," ",a("leadsPanel.convert")]}),e.jsx(k,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-muted-foreground hover:text-destructive",disabled:v.isPending,onClick:()=>v.mutate({id:i.id,status:"discarded"}),title:a("leadsPanel.discard"),
3children:e.jsx(Ds,{className:"w-3.5 h-3.5"})})]}),i.status==="converted"&&e.jsx(Fe,{className:"w-4 h-4 text-emerald-500 shrink-0"})]},i.id))})]})}function Ht(){const r=fe();return he({mutationFn:async a=>{const{data:s,error:l}=await K.functions.invoke("create-super-invoice",{body:a});if(l)throw l;if(s!=null&&s.error)throw new Error(s.message||s.error);return s},onSuccess:()=>{r.invalidateQueries({queryKey:["rental-history"]}),r.invalidateQueries({queryKey:["customers-list"]})},onError:async a=>{D.error(await Se(a,"Failed to create consolidated invoice"))}})}function $s(){const r=fe();return he({mutationFn:async a=>{var p;const{super_invoice_id:s,enable_reminders:l,...h}=a,{data:c,error:w}=await K.functions.invoke("send-invoice",{body:{...h,invoice_id:s}});if(w)throw w;if(l)try{const{data:j}=await K.from("invoices").select("id, customer_id, company_id, public_token, stripe_payment_link").eq("id",s).single();if(j){const v=new Date;v.setDate(v.getDate()+1),v.setHours(9,0,0,0);const _=a.payment_url||j.stripe_payment_link||(j.public_token?Ee(j.public_token):null);await K.from("payment_reminder_schedules").insert({invoice_id:j.id,company_id:j.company_id,customer_id:j.customer_id,order_id:null,payment_url:_,email_recipients:a.email_recipients??[],sms_phone:a.send_sms?(a.sms_phone||"").replace(/\D/g,""):null,send_email:(((p=a.email_recipients)==null?void 0:p.length)??0)>0,send_sms:!!a.send_sms,max_reminders:10,reminders_sent:0,next_reminder_at:v.toISOString(),status:"active"});const{data:g}=await K.from("invoices").select("id").eq("parent_super_invoice_id",j.id),i=(g??[]).map(b=>b.id);i.length&&await K.from("payment_reminder_schedules").update({status:"paused_by_super",updated_at:new Date().toISOString()}).in("invoice_id",i).eq("status","active")}}catch(j){console.error("[super-invoice] failed to schedule reminders:",j)}return r.invalidateQueries({queryKey:["rental-history"]}),r.invalidateQueries({queryKey:["customers-list"]}),c},onError:async a=>{D.error(await Se(a,"Failed to send invoice"))}})}function Os(){const r=fe();return he({mutationFn:async a=>{const{data:s,error:l}=await vt({body:{invoice_id:a.super_invoice_id,mode:a.mode??"charge"}});if(l)throw l;if((s==null?void 0:s.success)===!1)throw new Error(s.message||s.error||"Charge failed");return s},onSuccess:()=>{r.invalidateQueries({queryKey:["rental-history"]}),r.invalidateQueries({queryKey:["customers-list"]})},onError:async a=>{D.error(await Se(a,"Failed to charge card"))}})}function Vt(){const r=fe();return he({mutationFn:async a=>{const{data:s,error:l}=await K.functions.invoke("cancel-super-invoice",{body:{super_invoice_id:a}});if(l)throw l;if(s!=null&&s.error)throw new Error(s.message||s.error);return s},onSuccess:()=>{r.invalidateQueries({queryKey:["rental-history"]}),r.invalidateQueries({queryKey:["customers-list"]}),D.success("Consolidated invoice cancelled")},onError:async a=>{D.error(await Se(a,"Failed to cancel consolidated invoice"))}})}function qs(){const r=fe();return he({mutationFn:async a=>{const{data:s,error:l}=await K.functions.invoke("update-super-invoice",{body:a});if(l)throw l;if(s!=null&&s.error)throw new Error(s.message||s.error);return s},onSuccess:()=>{r.invalidateQueries({queryKey:["rental-history"]}),r.invalidateQueries({queryKey:["customers-list"]})},onError:async a=>{D.error(await Se(a,"Failed to update consolidated invoice"))}})}function Kt({open:r,onOpenChange:a,customer:s,children:l,onCreated:h}){var V;const{formatCurrency:c}=Ne(),{t:w}=Me(),[p,j]=o.useState("customer_pays"),[v,_]=o.useState(!1),{config:g}=jt(),i=o.useRef(!1);o.useEffect(()=>{!i.current&&(g!=null&&g.cardFeeHandling)&&(_(g.cardFeeHandling==="company_absorbs"),i.current=!0)},[g==null?void 0:g.cardFeeHandling]);const[b,P]=o.useState("review"),[m,I]=o.useState(null),U=Ht(),f=$s(),A=Os(),[te,n]=o.useState(!1),[L,J]=o.useState(null),Z=o.useMemo(()=>l.reduce((C,y)=>C+Number(y.total||0),0),[l]),u=async C=>{const y=v?"company_absorbs":"customer_pays";j(y);try{const N=await U.mutateAsync({customer_id:s.id,company_id:s.company_id,child_invoice_ids:l.map(T=>T.invoice_id),card_fee_handling:y}),{data:X}=await K.from("invoices").select("public_token").eq("id",N.super_invoice_id).maybeSingle(),se=X!=null&&X.public_token?Ee(X.public_token):null;if(I({super_invoice_id:N.super_invoice_id,invoice_number:N.invoice_number,total:N.total,payment_url:N.payment_url,invoice_url:se}),!N.payment_url&&N.payment_link_error&&D.warning(w("payLink.superNoLinkWarning")),C){const T=s.email?[s.email]:[],oe=s.phone||"";await f.mutateAsync({super_invoice_id:N.super_invoice_id,email_recipients:T,send_sms:!!oe,sms_phone:oe,send_admin_copy:!0,payment_url:N.payment_url}).catch(()=>{}),D.success(`Consolidated invoice ${N.invoice_number} sent to customer`)}else N.idempotent?D.success(`Reusing existing consolidated invoice ${N.invoice_number}`):D.success(`Consolidated invoice ${N.invoice_number} created`);P("done"),h==null||h(N.super_invoice_id)}catch{}},$=async()=>{const C=(m==null?void 0:m.invoice_url)||(m==null?void 0:m.payment_url);if(!C){D.error("No invoice link available");return}try{if(!await Es(C))throw new Error("copy failed");D.success("Invoice link copied")}catch{D.error("Failed to copy link")}},z=async()=>{var C;if(m!=null&&m.super_invoice_id)try{const y=await A.mutateAsync({super_invoice_id:m.super_invoice_id});J({last4:y==null?void 0:y.card_last4,brand:y==null?void 0:y.card_brand}),D.success(`Charged ${((C=y==null?void 0:y.card_brand)==null?void 0:C.toUpperCase())??"card"} â¢â¢â¢â¢ ${(y==null?void 0:y.card_last4)??""} for ${c((y==null?void 0:y.amount_charged)??m.total)}`)}catch{}},H=async()=>{var C;
3if(m!=null&&m.super_invoice_id){n(!0);try{const{data:y}=await K.auth.getSession(),N=(C=y.session)==null?void 0:C.access_token,se=await fetch("https://gcwyoiihrupbfqqlcurh.supabase.co/functions/v1/generate-super-invoice-pdf",{method:"POST",headers:{Authorization:`Bearer ${N}`,"Content-Type":"application/json",apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imdjd3lvaWlocnVwYmZxcWxjdXJoIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzAzMjEyNjYsImV4cCI6MjA4NTg5NzI2Nn0.8gf5NaCkH-Cg6dj4BgNKttLO7ywy89zuYvk1VG-Txpg"},body:JSON.stringify({super_invoice_id:m.super_invoice_id})});if(!se.ok)throw new Error("Failed to generate PDF");const T=await se.text(),oe=new Blob([T],{type:"text/html"}),we=URL.createObjectURL(oe);window.open(we,"_blank","noopener")}catch(y){D.error((y==null?void 0:y.message)||"Failed to open consolidated PDF")}finally{n(!1)}}},O=U.isPending||f.isPending||A.isPending;return e.jsx(Le,{open:r,onOpenChange:C=>{O||a(C)},children:e.jsxs($e,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Oe,{children:[e.jsxs(qe,{className:"flex items-center gap-2",children:[e.jsx(ie,{className:"w-5 h-5 text-primary"}),b==="review"?"Consolidate Invoices":"Consolidated Invoice Created"]}),e.jsx(Re,{children:b==="review"?e.jsxs(e.Fragment,{children:["Combine ",l.length," unpaid invoices for ",e.jsx("strong",{children:s.full_name})," into a single payment."]}):e.jsxs(e.Fragment,{children:["Invoice ",e.jsx("strong",{children:m==null?void 0:m.invoice_number})," ready to share."]})})]}),b==="review"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"rounded-lg border border-border bg-muted/20 divide-y divide-border/40",children:l.map(C=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsxs(ee,{variant:"outline",className:"font-mono text-[10px]",children:["#",C.invoice_number]}),C.has_extras&&e.jsx(ee,{variant:"secondary",className:"text-[10px]",children:"extras"})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[C.tax>0&&e.jsxs("span",{children:["tax ",c(C.tax)]}),C.fuel_surcharge>0&&e.jsxs("span",{children:["fuel ",c(C.fuel_surcharge)]}),C.processing_fee>0&&e.jsxs("span",{children:["fee ",c(C.processing_fee)]}),e.jsx("span",{className:"font-semibold text-foreground tabular-nums",children:c(C.total)})]})]},C.invoice_id))}),e.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 p-4 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-muted-foreground font-medium",children:"Total to charge"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums mt-0.5",children:c(Z)}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:"Includes taxes, fuel surcharges and extra charges from each invoice."})]}),e.jsx(ie,{className:"w-10 h-10 text-primary/30"})]}),e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border p-3",children:[e.jsx(Te,{checked:v,onCheckedChange:_,id:"absorb-fee"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(Ze,{htmlFor:"absorb-fee",className:"text-sm font-medium cursor-pointer",children:"Company absorbs card processing fee"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"By default the customer pays the card fee on top of the total. Toggle on to deduct it from your payout instead."})]})]}),e.jsxs("div",{className:"rounded-lg border border-border bg-muted/10 p-3 text-xs text-muted-foreground space-y-1",children:[e.jsx("p",{children:"⢠If the customer pays one of these invoices individually, it's automatically removed from this consolidated charge and the link recalculates."}),e.jsx("p",{children:"⢠Each underlying order keeps its own P&L, payout and accounting integrity."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 pt-2",children:[e.jsxs(k,{onClick:()=>u(!0),disabled:O,className:"flex-1 gap-2",children:[O?e.jsx(de,{className:"w-4 h-4 animate-spin"}):e.jsx(ss,{className:"w-4 h-4"}),"Create & Send to Customer"]}),e.jsxs(k,{variant:"outline",onClick:()=>u(!1),disabled:O,className:"flex-1 gap-2",children:[O?e.jsx(de,{className:"w-4 h-4 animate-spin"}):e.jsx(Xe,{className:"w-4 h-4"}),"Create & Copy Link"]})]})]}),b==="done"&&m&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border border-emerald-500/20 bg-emerald-500/5 p-4 flex items-center gap-3",children:[e.jsx(Fe,{className:"w-8 h-8 text-emerald-600 shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-semibold",children:m.invoice_number}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Total: ",e.jsx("span",{className:"font-semibold text-foreground",children:c(m.total)})]})]})]}),(m.invoice_url||m.payment_url)&&e.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-2",children:[e.jsx(Ze,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:m.invoice_url?"Invoice Link":"Payment Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(es,{readOnly:!0,value:m.invoice_url||m.payment_url||"",className:"text-xs"}),e.jsxs(k,{size:"sm",variant:"outline",onClick:$,className:"gap-1.5",children:[e.jsx(Xe,{className:"w-3.5 h-3.5"})," Copy"]})]}),e.jsxs("a",{href:m.invoice_url||m.payment_url||"#",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[m.invoice_url?"Open invoice page":"Open payment page"," ",e.jsx(zs,{className:"w-3 h-3"})]}),m.invoice_url&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"The invoice page shows the full breakdown and a Pay button for the customer."})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsxs(k,{variant:"default",onClick:z,disabled:A.isPending||L!==null,className:"gap-2",children:[A.isPending?e.jsx(de,{className:"w-4 h-4 animate-spin"}):e.jsx(ze,{className:"w-4 h-4"}),L?`Charged ${((V=L.brand)==null?void 0:V.toUpperCase())??""} â¢â¢â¢â¢ ${L.last4??""}`:"Charge Card on File"]}),e.jsxs(k,{variant:"outline",onClick:H,disabled:te,className:"gap-2",children:[te?e.jsx(de,{className:"w-4 h-4 animate-spin"}):e.jsx(Ms,{className:"w-4 h-4"}),"View / Print PDF"]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground text-center",children:"Charging the card on file uses the customer's saved Stripe payment method. Funds route to your connected account; platform & processor fees follow your current plan."}),e.jsx(ye,{}),e.jsx(k,{onClick:()=>a(!1),className:"w-full",children:"Done"})]})]})})}function Qt({open:r,onOpenChange:a,superInvoice:s,customerEmail:l,customerPhone:h,customerName:c}
3){const{toast:w}=Is(),{formatCurrency:p}=Ne(),j=$s(),[v,_]=o.useState(!0),[g,i]=o.useState(!1),[b,P]=o.useState(""),[m,I]=o.useState(!0);if(o.useEffect(()=>{r&&(_(!!l),i(!!h),P(Je(h||"")),I(!0))},[r,l,h]),!s)return null;const U=async()=>{if(!v&&!g){w({title:"Select a channel",description:"Enable Email and/or SMS to send.",variant:"destructive"});return}try{await j.mutateAsync({super_invoice_id:s.id,email_recipients:v&&l?[l]:[],send_sms:g,sms_phone:g?b.replace(/\D/g,""):"",send_admin_copy:m,payment_url:s.payment_url,enable_reminders:!0}),w({title:"Consolidated invoice sent",description:`#${s.invoice_number} delivered. 10-day automated reminders activated.`}),a(!1)}catch{}};return e.jsx(Le,{open:r,onOpenChange:a,children:e.jsxs($e,{className:"max-w-[440px] w-[95vw] p-0 gap-0 overflow-hidden",children:[e.jsx(Oe,{className:"p-5 pb-3 border-b border-border",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ie,{className:"w-4 h-4 text-primary"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs(qe,{className:"text-base font-semibold",children:["Send #",s.invoice_number]}),e.jsxs(Re,{className:"text-xs text-muted-foreground mt-0.5",children:["Choose how to send the consolidated invoice to ",c]})]})]})}),e.jsxs("div",{className:"p-5 space-y-5",children:[e.jsx("div",{className:"rounded-xl border border-border p-4 bg-muted/20",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ie,{className:"w-4 h-4 text-primary"}),e.jsx("span",{className:"text-sm font-semibold",children:s.invoice_number}),e.jsxs(ee,{variant:"secondary",className:"text-[10px] h-4 px-1.5",children:[s.child_count," invoice",s.child_count===1?"":"s"]})]}),e.jsx("span",{className:"text-sm font-semibold",children:p(s.total)})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-sm font-semibold",children:"Delivery options"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-medium",children:"Email"}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:l||"No email on file"})]})]}),e.jsx(Te,{checked:v,onCheckedChange:_,disabled:!l})]}),v&&e.jsxs("div",{className:"pl-6 flex items-center gap-2",children:[e.jsx(Te,{checked:m,onCheckedChange:I,className:"scale-75"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Send a copy to admin"})]}),e.jsx(ye,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tt,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-medium",children:"Text message"}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:h||"No phone on file"})]})]}),e.jsx(Te,{checked:g,onCheckedChange:i,disabled:!h})]}),g&&e.jsxs("div",{className:"pl-6 space-y-2",children:[e.jsx(Ze,{className:"text-xs text-muted-foreground",children:"Phone number"}),e.jsx(es,{value:b,onChange:f=>P(Je(f.target.value)),placeholder:"(555) 000-0000",className:"h-9 text-sm rounded-lg w-56"})]})]}),e.jsx(ye,{}),e.jsx("div",{className:"rounded-lg bg-primary/5 border border-primary/20 px-3 py-2 text-[11px] text-muted-foreground leading-relaxed",children:"After sending, automated daily reminders will run for up to 10 days (or until the consolidated invoice is paid) â same as a regular invoice."}),e.jsx(k,{className:"w-full h-10 gap-2",onClick:U,disabled:j.isPending||!v&&!g,children:j.isPending?e.jsxs(e.Fragment,{children:[e.jsx(de,{className:"w-4 h-4 animate-spin"})," Sendingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(ss,{className:"w-4 h-4"})," Send consolidated invoice"]})})]})]})})}function Jt({open:r,onOpenChange:a,superInvoice:s,customerName:l}){const{formatCurrency:h}=Ne(),c=Os(),[w,p]=o.useState(!1),[j,v]=o.useState(null),[_,g]=o.useState(null),[i,b]=o.useState(!1),[P,m]=o.useState(!1);if(o.useEffect(()=>{!r||!s||(b(!1),m(!1),g(null),v(null),p(!0),c.mutateAsync({super_invoice_id:s.id,mode:"preview"}).then(f=>{f!=null&&f.has_card?g({brand:f.card_brand||"card",last4:f.card_last4||"â¢â¢â¢â¢"}):v((f==null?void 0:f.message)||"No card on file for this customer.")}).catch(f=>v((f==null?void 0:f.message)||"Failed to look up card on file")).finally(()=>p(!1)))},[r,s==null?void 0:s.id]),!s)return null;const I=!!_&&i&&P&&!c.isPending,U=async()=>{try{const f=await c.mutateAsync({super_invoice_id:s.id,mode:"charge"});D.success(`Charged ${((f==null?void 0:f.card_brand)||"card").toUpperCase()} â¢â¢â¢â¢ ${(f==null?void 0:f.card_last4)??""}`),a(!1)}catch{}};return e.jsx(Le,{open:r,onOpenChange:a,children:e.jsxs($e,{className:"max-w-[460px] w-[95vw]",children:[e.jsxs(Oe,{children:[e.jsxs(qe,{className:"flex items-center gap-2 text-base",children:[e.jsx(ie,{className:"w-4 h-4 text-primary"}),"Charge consolidated invoice"]}),e.jsx(Re,{className:"text-xs",children:"Review carefully â this will charge the customer's saved card immediately."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl border border-border bg-muted/30 px-4 py-3 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Consolidated invoice"}),e.jsxs("span",{className:"font-semibold font-mono",children:["#",s.invoice_number]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Customer"}),e.jsx("span",{className:"font-medium truncate max-w-[60%] text-right",children:l})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Invoices included"}),e.jsx("span",{className:"font-medium",children:s.child_count})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border pt-2 mt-1",children:[e.jsx("span",{className:"text-sm font-semibold",children:"Amount to charge"}),e.jsx("span",{className:"text-lg font-bold tabular-nums",children:h(s.total)})]})]}),e.jsxs("div",{className:"rounded-xl border border-border px-4 py-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground mb-1.5",children:"Card on file"}),w?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(de,{className:"w-4 h-4 animate-spin"})," Looking up saved cardâ¦"]}):j?e.jsxs("div",{className:"flex items-start gap-2 text-sm text-destructive",children:[e.jsx(bs,{className:"w-4 h-4 mt-0.5 shrink-0"}),e.jsx("span",{children:j})]}):_?e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-9 h-9 rounded-md bg-primary/10 flex items-center justify-center",children:e.jsx(ze,{className:"w-4 h-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-semibold capitalize",children:[_.brand," â¢â¢â¢â¢ ",_.last4]}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Saved card · will be charged off-session"})]})]}):null]}),_&&e.jsxs("div",{className:"space-y-2.5 rounded-xl border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-[12px] text-foreground
3/90 leading-relaxed",children:[e.jsx(bs,{className:"w-4 h-4 mt-0.5 text-amber-600 shrink-0"}),e.jsx("p",{children:"By charging this card you accept full responsibility for this transaction. Disputed or refunded charges may incur additional fees and impact your account standing. Make sure you have authorization from the customer."})]}),e.jsxs("label",{className:"flex items-start gap-2 cursor-pointer text-[12px] leading-relaxed",children:[e.jsx(Ae,{checked:i,onCheckedChange:f=>b(!!f),className:"mt-0.5"}),e.jsxs("span",{children:["I have authorization from ",e.jsx("strong",{children:l})," to charge this card for ",h(s.total),"."]})]}),e.jsxs("label",{className:"flex items-start gap-2 cursor-pointer text-[12px] leading-relaxed",children:[e.jsx(Ae,{checked:P,onCheckedChange:f=>m(!!f),className:"mt-0.5"}),e.jsxs("span",{children:["I understand this charge is ",e.jsx("strong",{children:"final and immediate"}),", and I take responsibility for any chargebacks or disputes."]})]})]})]}),e.jsxs(at,{className:"gap-2 sm:gap-2",children:[e.jsx(k,{variant:"outline",onClick:()=>a(!1),disabled:c.isPending,children:"Cancel"}),e.jsx(k,{onClick:U,disabled:!I,className:"gap-2",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(de,{className:"w-4 h-4 animate-spin"})," Chargingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(ze,{className:"w-4 h-4"})," Charge ",_?`${h(s.total)}`:""]})})]})]})})}const Yt=(r,a)=>{const s=(a||r||"").toLowerCase();return s==="paid"?{label:"Paid",cls:"bg-emerald-500/10 text-emerald-600 border-emerald-500/30"}:s==="partially_paid"?{label:"Partially paid",cls:"bg-amber-500/10 text-amber-600 border-amber-500/30"}:s==="overdue"?{label:"Overdue",cls:"bg-destructive/10 text-destructive border-destructive/30"}:s==="cancelled"||s==="void"?{label:"Cancelled",cls:"bg-muted text-muted-foreground border-border"}:s==="open"||s==="sent"?{label:"Sent",cls:"bg-primary/10 text-primary border-primary/30"}:{label:s||"Open",cls:"bg-primary/10 text-primary border-primary/30"}},ks=r=>{if(!r)return"â";try{return new Date(r).toLocaleDateString("en-US",{month:"short",day:"numeric"})}catch{return r}};function Zt({superInvoices:r,customer:a,onAddInvoices:s,addingToSuperId:l,onCancelAdding:h}){const{formatCurrency:c}=Ne(),[w,p]=o.useState(null),[j,v]=o.useState(null),[_,g]=o.useState(null),[i,b]=o.useState(null),P=Vt(),m=qs();if(!(r!=null&&r.length))return null;const I=async n=>{const L=n.public_token?Ee(n.public_token):n.payment_url;if(!L){D.error("No public invoice link available yet â try Resend to regenerate.");return}try{if(!await Es(L))throw new Error("copy failed");D.success("Invoice link copied")}catch{D.error("Failed to copy link")}},U=async n=>{const L=n.public_token?Ee(n.public_token):n.payment_url;if(!L){D.error("No invoice link available yet");return}window.open(L,"_blank","noopener")},f=n=>{g(n)},A=n=>{b(n)},te=async(n,L)=>{try{await m.mutateAsync({super_invoice_id:n.id,remove_child_invoice_ids:[L]}),D.success("Invoice removed from consolidation")}catch{}};return e.jsxs("div",{className:"mb-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:[e.jsx(ie,{className:"w-3.5 h-3.5"}),"Active Consolidated Invoices",e.jsx(ee,{variant:"secondary",className:"text-[10px] h-4 px-1.5",children:r.length})]}),r.map(n=>{const L=Yt(n.status,n.super_status),J=w===n.id,Z=n.super_status==="cancelled"||n.status==="cancelled",u=n.super_status==="paid"||n.status==="paid",$=!Z&&!u,z=l===n.id,H=!!l&&!z,O=n.total&&n.total>0?n.total:u?n.children_paid_total??n.children_total??0:n.children_total??0;return e.jsxs("div",{className:Y("rounded-lg border overflow-hidden min-w-0 transition-all",u?"border-emerald-500/30 bg-gradient-to-br from-emerald-500/10 to-transparent":"border-primary/20 bg-gradient-to-br from-primary/5 to-transparent",z&&"ring-2 ring-primary ring-offset-2 ring-offset-background shadow-lg border-primary/60",H&&"opacity-60"),children:[u&&e.jsxs("div",{className:"px-3 py-1.5 bg-emerald-500/15 border-b border-emerald-500/20 text-[11px] font-semibold text-emerald-700 dark:text-emerald-400 flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-flex w-1.5 h-1.5 rounded-full bg-emerald-500"}),"Paid · ",c(O)," · all ",n.child_count," child invoice",n.child_count===1?"":"s"," settled"]}),e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-2 md:gap-3 px-2 sm:px-3 py-2.5 min-w-0",children:[e.jsxs("button",{type:"button",className:"flex items-start gap-2 min-w-0 flex-1 text-left",onClick:()=>p(J?null:n.id),children:[J?e.jsx(Fs,{className:"w-4 h-4 text-muted-foreground shrink-0 mt-0.5"}):e.jsx(We,{className:"w-4 h-4 text-muted-foreground shrink-0 mt-0.5"}),e.jsx(ie,{className:Y("w-4 h-4 shrink-0 mt-0.5",u?"text-emerald-600":"text-primary")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 min-w-0",children:[e.jsxs("span",{className:"font-mono text-xs sm:text-sm font-semibold truncate min-w-0",children:["#",n.invoice_number]}),e.jsx("span",{className:"text-sm font-bold tabular-nums shrink-0 whitespace-nowrap md:hidden",children:c(O)})]}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap mt-1 min-w-0",children:[e.jsx("span",{className:Y("text-[10px] font-semibold px-2 py-0.5 rounded-full border",L.cls),children:L.label}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[n.child_count," invoice",n.child_count===1?"":"s"]})]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground mt-0.5 truncate",children:["Created ",ks(n.created_at)," · Due ",ks(n.due_date)]})]}),e.jsx("div",{className:"ml-4 shrink-0 text-right hidden md:block",children:e.jsx("div",{className:"text-base font-bold tabular-nums",children:c(O)})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 w-full min-w-0 md:w-auto md:flex md:flex-wrap md:items-center md:border-l md:border-border md:pl-3",children:[e.jsxs(k,{size:"sm",variant:"ghost",className:"h-8 md:h-7 w-full md:w-auto gap-1.5 text-[11px] sm:text-xs justify-center min-w-0",onClick:()=>U(n),disabled:j===n.id,children:[j===n.id?e.jsx(de,{className:"w-3 h-3 animate-spin"}):e.jsx(Ms,{className:"w-3 h-3"})," View"]}),e.jsxs(k,{size:"sm",variant:"ghost",className:"h-8 md:h-7 w-full md:w-auto gap-1.5 text-[11px] sm:text-xs justify-center min-w-0",onClick:()=>I(n),disabled:!n.public_token&&!n.payment_url,title:"Copy public invoice link (payment link is inside the invoice page)",children:[e.jsx(Xe,{className:"w-3 h-3"})," Copy link"]}),$&&e.jsxs(e.Fragment,{children:[e.jsxs(k,{size:"sm",variant:"ghost",className:"h-8 md:h-7 w-full md:w-auto gap-1.5 text-[11px] sm:text-xs justify-center min-w-0",onClick:()=>f(n),children:[e.jsx(ss,{className:"w-3 h-3"})," Resend"]}),s&&(z?e.jsxs(k,{size:"sm",variant:"secondary",className:"h-8 md:h-7 w-full md:w-auto gap-1.5 text-[11px] sm:text-xs justify-center min-w-0",onClick:()=>h==null?void 0:h(),children:[e.jsx(De,{className:"w-3 h-3"})," Cancel adding"]}):e.jsxs(k,{size:"sm",variant:"outline",className:"h-8 md:h-7 w-full md:w-auto gap-1.5 text-[11px] sm:text-xs justify-center min-w-0",onClick:()=>s(n.id),children:[e.jsx(Ls,{className:"w-3 h-3"})," Add invoices"]})),e.jsxs(k,{size:"sm",variant:"default",className:"h-8 md:h-7 col-span-2 md:col-span-1 w-full md:w-auto gap-1.5 text-[11px] sm:text-xs justify-center min-w-0",onClick:()=>A(n),children:[e.jsx(ze,{className:"w-3 h-3"})," Charge card"]}),e.jsxs(bt,{children:[e.jsx(yt,{asChild:!0,children:e.jsxs(k,{size:"sm",variant:"ghost",className:"h-8 md:h-7 col-span-2 md:col-span-1 w-full md:w-auto gap-1.5 text-[11px] sm:text-xs justify-center text-destructive hover:text-destructive hover:bg-destructive/10 min-w-0",children:[e.jsx(Dt,{className:"w-3 h-3"})," Cancel"]})}),e.jsxs(Nt,{children:[e.jsxs(wt,{children:[e.jsx(_t,{children:"Cancel consolidated invoice?"}),e.jsxs(Ct,{children:["This will void the consolidated invoice ",e.jsxs("strong",{children:["#",n.invoice_number]})," and detach all"," ",e.jsx("strong",{children:n.child_count})," child invoices. The original invoices remain unpaid and selectable again. This cannot be undone."]})]}),e.jsxs(St,{children:[e.jsx(kt,{children:"Keep it"}),e.jsx(It,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>
3P.mutate(n.id),children:"Yes, cancel"})]})]})]})]})]})]}),J&&e.jsxs("div",{className:"border-t border-border/60 bg-background/40 px-2 sm:px-3 py-2 space-y-1 min-w-0",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider font-semibold text-muted-foreground",children:"Included invoices"}),n.children.length===0?e.jsx("div",{className:"text-xs text-muted-foreground py-1",children:"No children remaining."}):n.children.map(V=>e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 sm:gap-2 text-xs py-1.5 px-2 rounded-md hover:bg-muted/30 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsxs("span",{className:"font-mono truncate",children:["#",V.invoice_number]}),e.jsx(ee,{variant:"outline",className:"text-[9px] capitalize h-4 px-1.5 shrink-0",children:V.status})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0 self-end sm:self-auto",children:[e.jsx("span",{className:"font-semibold tabular-nums",children:c(V.total)}),$&&V.status!=="paid"&&e.jsx(k,{size:"sm",variant:"ghost",className:"h-6 text-[10px] text-muted-foreground hover:text-destructive",onClick:()=>te(n,V.id),disabled:m.isPending,children:"Remove"})]})]},V.id)),n.payment_url&&!u&&e.jsxs("a",{href:n.payment_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-[11px] text-primary hover:underline mt-1",children:["Open public payment page ",e.jsx(zs,{className:"w-3 h-3"})]})]})]},n.id)}),e.jsx(Qt,{open:!!_,onOpenChange:n=>{n||g(null)},superInvoice:_,customerName:a.name,customerEmail:a.email??null,customerPhone:a.phone??null}),e.jsx(Jt,{open:!!i,onOpenChange:n=>{n||b(null)},superInvoice:i,customerName:a.name})]})}function Wn(){const{t:r}=Me(),{formatCurrency:a,formatDate:s}=Ne(),{user:l}=Ge(),h=l==null?void 0:l.companyId,[c]=Zs(),w=c.get("tab")==="estimates";o.useState(w);const{data:p=[],isLoading:j}=Ps({queryKey:["customers-list",h],queryFn:async()=>{const{data:t,error:d}=await K.from("customers").select("*, contractor_data, broker_data").eq("company_id",h).is("deleted_at",null).order("first_name");if(d)throw d;return t},enabled:!!h}),{data:v}=Gs(),_=tt(),g=o.useMemo(()=>{const t=p.length,d=(v==null?void 0:v.orders)??[],E=d.filter(q=>q.paymentStatus!=="declined"&&q.paymentStatus!=="abandoned"&&!q._isCompleted).length,M=ps(new Date,_),[S,me]=M.split("-"),ae=`${S}-${me}-01`,[R]=hs(ae,_),W=new Date(`${ae}T12:00:00.000Z`);W.setUTCMonth(W.getUTCMonth()+1);const je=ps(W,_).slice(0,8)+"01",[x]=hs(je,_),F=Date.parse(R),Q=Date.parse(x),B=d.reduce((q,le)=>{var ne,ue;if(le.paymentStatus!=="paid")return q;const ve=(ne=le.paymentInfo)==null?void 0:ne.paymentDate;if(!ve)return q;const be=Date.parse(ve);return Number.isNaN(be)||be<F||be>=Q?q:q+Number(((ue=le.paymentInfo)==null?void 0:ue.invoiceTotal)??le.total??0)},0);return[{label:r("customers.totalCustomers"),value:t,icon:ys,format:q=>q.toString()},{label:r("customers.activeRentals"),value:E,icon:Ft,format:q=>q.toString()},{label:r("customers.revenueThisMonth"),value:B,icon:At,format:q=>a(q)},{label:r("customers.contractors"),value:p.filter(q=>q.customer_type==="contractor").length,icon:Qe,format:q=>q.toString()}]},[p,v,_,r,a]),[i,b]=o.useState(""),[P,m]=o.useState("all"),[I,U]=o.useState("all"),f=Ws(),[A,te]=o.useState("name"),[n,L]=o.useState("asc"),[J,Z]=o.useState(new Set),[u,$]=o.useState(null),[z,H]=o.useState(1),[O,V]=o.useState(10),[C,y]=o.useState(!1),[N,X]=o.useState(null),[se,T]=o.useState(!1),[oe,we]=o.useState(null),[ke,ts]=o.useState(null),[rs,as]=o.useState({}),[ge,ns]=o.useState(null),[is,Ie]=o.useState({}),os=qs(),[Rs,Bs]=o.useState(()=>typeof window>"u"?!1:localStorage.getItem("dc_consolidate_tip_dismissed")!=="1"),Pe=()=>{Bs(!1);try{localStorage.setItem("dc_consolidate_tip_dismissed","1")}catch{}},Us=t=>{we(d=>d===t?d:t),Pe(),requestAnimationFrame(()=>{setTimeout(()=>{const d=document.querySelector(`[data-customer-expanded="${t}"]`);d&&d.scrollIntoView({behavior:"smooth",block:"start"})},80)})},re=v,ls=o.useMemo(()=>{const t=new Map;
3return((re==null?void 0:re.orders)??[]).forEach(d=>{if(!d._customerId)return;const E=t.get(d._customerId)??[];E.push(d),t.set(d._customerId,E)}),t},[re]),cs=t=>{const d=(t._invoiceStatus??"").toLowerCase();return t._invoiceId?d!=="sent"&&d!=="overdue"?{selectable:!1,reason:`Status: ${d||"unknown"}`}:t._parentSuperInvoiceId?{selectable:!1,reason:"Already in another consolidated invoice"}:{selectable:!0}:{selectable:!1,reason:"No invoice"}},ds=(t,d,E)=>{as(M=>{const S=new Set(M[t]??[]);return E?S.add(d):S.delete(d),{...M,[t]:S}})},_e=t=>{as(d=>{const E={...d};return delete E[t],E})},Hs=t=>{A===t?L(d=>d==="asc"?"desc":"asc"):(te(t),L("desc"))},pe=o.useMemo(()=>{let t=[...p];if(i){const d=i.toLowerCase();t=t.filter(E=>`${E.first_name} ${E.last_name}`.toLowerCase().includes(d)||(E.company_name??"").toLowerCase().includes(d)||(E.email??"").toLowerCase().includes(d))}return P!=="all"&&(P==="active"?t=t.filter(d=>d.is_active):P==="inactive"&&(t=t.filter(d=>!d.is_active))),I!=="all"&&(t=t.filter(d=>d.customer_type===I)),t.sort((d,E)=>{let M=0;return A==="name"?M=`${d.first_name} ${d.last_name}`.localeCompare(`${E.first_name} ${E.last_name}`):A==="lifetimeValue"?M=Number(d.lifetime_value)-Number(E.lifetime_value):A==="totalOrders"&&(M=d.total_orders-E.total_orders),n==="asc"?M:-M}),t},[i,P,I,A,n,p]);o.useEffect(()=>H(1),[i,P,I,A,n]);const ms=o.useMemo(()=>{const t=(z-1)*O;return pe.slice(t,t+O)},[pe,z,O]),us=pe.length>0&&pe.every(t=>J.has(t.id)),Vs=()=>Z(us?new Set:new Set(pe.map(t=>t.id))),Ks=t=>{const d=new Set(J);d.has(t)?d.delete(t):d.add(t),Z(d)},Qs=t=>t==="contractor"?e.jsx(Qe,{className:"w-4 h-4"}):t==="commercial"?e.jsx(_s,{className:"w-4 h-4"}):t==="broker"?e.jsx(ws,{className:"w-4 h-4"}):e.jsx(Ns,{className:"w-4 h-4"}),Js=t=>t==="contractor"?"bg-amber-100 text-amber-700":t==="commercial"?"bg-sky-100 text-sky-700":t==="broker"?"bg-purple-100 text-purple-700":"bg-primary/10 text-primary",Ys=t=>t==="contractor"?"bg-amber-50 text-amber-700":t==="commercial"?"bg-sky-50 text-sky-700":t==="broker"?"bg-purple-50 text-purple-700":"bg-primary/10 text-primary",Be=({label:t,sk:d})=>e.jsxs("button",{onClick:()=>Hs(d),className:"flex items-center gap-1 group",children:[e.jsx("span",{children:t}),e.jsx(zt,{className:Y("w-3 h-3 transition-colors",A===d?"text-foreground":"text-transparent group-hover:text-muted-foreground")})]});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl font-semibold text-foreground tracking-tight",children:r("customers.title")}),e.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground mt-1",children:r("customers.subtitle")})]}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(Xs,{}),e.jsxs(k,{variant:"outline",size:"sm",className:"h-9 gap-1.5 rounded-lg text-sm",onClick:()=>T(!0),children:[e.jsx(Ye,{className:"w-3.5 h-3.5"})," ",r("actions.import")]}),e.jsxs(k,{size:"sm",className:"h-9 gap-1.5 rounded-lg text-sm",onClick:()=>y(!0),children:[e.jsx(Ls,{className:"w-3.5 h-3.5"})," ",r("customers.newCustomer")]})]})]}),e.jsx(lt,{defaultExpanded:w}),e.jsx(Ut,{defaultExpanded:c.get("tab")==="leads"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4",children:g.map(t=>e.jsxs("div",{className:"rounded-xl border border-border bg-card p-5 shadow-[0_1px_3px_0_hsl(var(--foreground)/0.04)]",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-[12px] font-medium text-muted-foreground uppercase tracking-wider",children:t.label}),e.jsx(t.icon,{className:"w-4 h-4 text-muted-foreground/50"})]}),e.jsx("p",{className:"text-2xl font-semibold text-foreground mt-2 tracking-tight",children:t.format(t.value)})]},t.label))}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1 sm:max-w-md",children:[e.jsx(Et,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(es,{placeholder:r("customers.searchCustomers"),value:i,onChange:t=>b(t.target.value),className:"pl-9 h-9 rounded-lg text-sm border-border"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3",children:[e.jsxs(fs,{value:P,onValueChange:m,children:[e.jsx(gs,{className:"w-[130px] h-9 rounded-lg text-sm",children:e.jsx(js,{placeholder:r("common.status")})}),e.jsxs(vs,{children:[e.jsx(xe,{value:"all",children:r("customers.allStatus")}),e.jsx(xe,{value:"active",children:r("common.active")}),e.jsx(xe,{value:"inactive",children:r("common.inactive")})]})]}
3),e.jsxs(fs,{value:I,onValueChange:U,children:[e.jsx(gs,{className:"w-[150px] h-9 rounded-lg text-sm",children:e.jsx(js,{placeholder:r("common.type")})}),e.jsxs(vs,{children:[e.jsx(xe,{value:"all",children:r("customers.allTypes")}),e.jsx(xe,{value:"residential",children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ns,{className:"w-3.5 h-3.5"})," ",r("customers.residential")]})}),e.jsx(xe,{value:"contractor",children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Qe,{className:"w-3.5 h-3.5"})," ",r("customers.contractor")]})}),e.jsx(xe,{value:"broker",children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ws,{className:"w-3.5 h-3.5"})," ",r("customers.broker")]})}),f&&e.jsx(xe,{value:"commercial",children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(_s,{className:"w-3.5 h-3.5"})," ",r("commercialAccount.types.commercial")]})})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground ml-auto whitespace-nowrap",children:[pe.length," ",r("customers.title").toLowerCase()]})]})]}),Rs&&e.jsxs("div",{className:"flex items-start gap-3 rounded-xl border border-primary/20 bg-primary/[0.04] px-4 py-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(As,{className:"w-4 h-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Consolidate multiple invoices into one payment"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Click the ",e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded bg-primary/10 text-primary font-medium",children:[e.jsx(Cs,{className:"w-3 h-3"})," orders"]})," pill or the arrow on a customer row to view their orders and create a Super Invoice. Clicking the row itself opens the customer drawer."]})]}),e.jsx("button",{type:"button",onClick:Pe,className:"w-7 h-7 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted shrink-0","aria-label":"Dismiss tip",children:e.jsx(De,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"rounded-xl border border-border bg-card shadow-[0_1px_3px_0_hsl(var(--foreground)/0.04)] overflow-hidden overflow-x-auto",children:[e.jsxs(dt,{children:[e.jsx(mt,{children:e.jsxs(Ce,{className:"hover:bg-transparent bg-muted/30",children:[e.jsx(ce,{className:"w-[32px]"}),e.jsx(ce,{className:"w-[40px]",children:e.jsx(Ae,{checked:us,onCheckedChange:Vs})}),e.jsx(ce,{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground",children:e.jsx(Be,{label:r("common.name"),sk:"name"})}),e.jsx(ce,{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground",children:r("common.type")}),e.jsx(ce,{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground",children:r("common.company")}),e.jsx(ce,{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground",children:r("common.phone")}),e.jsx(ce,{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground whitespace-nowrap",children:e.jsx(Be,{label:r("customers.lifetimeValue"),sk:"lifetimeValue"})}),e.jsx(ce,{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground",children:e.jsx(Be,{label:r("customers.orders"),sk:"totalOrders"})}),e.jsx(ce,{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground",children:r("common.status")})]})}),e.jsx(ut,{children:j?e.jsx(Ce,{children:e.jsx(G,{colSpan:10,className:"py-16 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loadingâ¦"})})}):ms.length>0?ms.map((t,d)=>{const E=`${t.first_name} ${t.last_name}`,M=oe===t.id,S=ls.get(t.id)??[],me=S.filter(R=>{const je=(R._invoiceStatus??R.invoice_status??R.payment_status??"").toString().toLowerCase()==="paid",x=!!R._parentSuperInvoiceId;return!je&&!x&&!!R._invoiceId}).length,ae=S.length||Number(t.total_orders)||0;return e.jsxs(o.Fragment,{children:[e.jsxs(Ce,{className:Y("group cursor-pointer transition-colors",d%2===1&&"bg-muted/15",J.has(t.id)&&"bg-primary/[0.03]",M&&"bg-primary/[0.04]"),onClick:()=>X(t),onMouseEnter:()=>$(t.id),onMouseLeave:()=>$(null),children:[e.jsx(G,{className:"py-3.5 pr-0",onClick:R=>R.stopPropagation(),children:e.jsx(Ue,{delayDuration:150,children:e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>{Pe(),we(M?null:t.id)},className:Y("w-8 h-8 rounded-lg flex items-center justify-center transition-all",M?"bg-primary/15 text-primary":ae>0?"bg-muted/60 text-primary hover:bg-primary/10":"bg-muted/40 text-muted-foreground hover:bg-muted"),"aria-label":M?"Collapse orders":"Expand orders",children:e.jsx(We,{className:Y("w-4 h-4 transition-transform",M&&"rotate-90")})})}),e.jsx(Ke,{side:"right",children:"View orders & consolidate invoices"})]})})}),e.jsx(G,{className:"py-3.5",onClick:R=>R.stopPropagation(),children:e.jsx(Ae,{checked:J.has(t.id),onCheckedChange:()=>Ks(t.id)})}),e.jsx(G,{className:"py-3.5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Y("w-8 h-8 rounded-full flex items-center justify-center shrink-0",Js(t.customer_type)),children:Qs(t.customer_type)}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-foreground leading-tight",children:E}),me>=2&&e.jsxs("button",{type:"button",onClick:R=>{R.stopPropagation(),Us(t.id)},className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-full bg-amber-100 text-amber-700 hover:bg-amber-200 transition-colors animate-pulse","aria-label":`Consolidate ${me} unpaid invoices`,children:[e.jsx(ie,{className:"w-3 h-3"}),"Consolidate ",me," unpaid"]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:t.email??"â"})]})]})}),e.jsx(G,{className:"py-3.5",children:e.jsx("span",{className:Y("text-[10px] font-medium px-2 py-0.5 rounded-full capitalize",Ys(t.customer_type)),children:t.customer_type})}),e.jsx(G,{className:"text-sm text-muted-foreground py-3.5 whitespace-nowrap",children:t.company_name||"â"}),e.jsx(G,{className:"text-sm text-muted-foreground py-3.5 whitespace-nowrap",children:t.phone?Je(t.phone):"â"}),e.jsx(G,{className:"text-sm font-medium text-foreground py-3.5",children:a(Number(t.lifetime_value))}),e.jsx(G,{className:"py-3.5",onClick:R=>R.stopPropagation(),children:ae>0?e.jsx(Ue,{delayDuration:150,children:e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{Pe(),we(M?null:t.id)},className:Y("inline-flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full border transition-all",M?"bg-primary/10 border-primary/30 text-primary":"bg-muted/40 border-border text-foreground hover:bg-primary/10 hover:border-primary/30 hover:text-primary"),"aria-label":`View ${ae} orders`,children:[e.jsx(Cs,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"tabular-nums",children:ae}),e.jsx(We,{className:Y("w-3 h-3 -mr-0.5 transition-transform",M&&"rotate-90")})]})}),e.jsx(Ke,{children:"View orders & consolidate invoices"})]})}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"0"})}),e.jsx(G,{className:"py-3.5",children:e.jsx("span",{className:Y("text-[11px] font-medium px-2.5 py-1 rounded-full",t.is_active?"bg-emerald-50 text-emerald-700":"bg-muted text-muted-foreground"),children:t.is_active?r("common.active"):r("common.inactive")})})]},t.id),M&&(()=>{const R=rs[t.id]??new Set,W=S.filter(x=>x._invoiceId&&R.has(x._invoiceId)).map(x=>{var F,Q;return{invoice_id:x._invoiceId,invoice_number:x._invoiceNumber??"â",order_id:x.id,total:Number(x._invoiceTotal??x.total??0),tax:Number(((F=x.paymentInfo)==null?void 0:F.salesTax)??0),fuel_surcharge:Number(((Q=x.paymentInfo)==null?void 0:Q.fuelSurcharge)??0),processing_fee:Number(x._invoiceProcessingFee??0),has_extras:(x.overweightAmount??0)>0||(x._extraCharges??[]).length>0}}),je=W.reduce((x,F)=>x+F.total,0);
3return e.jsx(Ce,{"data-customer-expanded":t.id,className:"hover:bg-transparent bg-muted/10",children:e.jsx(G,{colSpan:10,className:"p-0",children:e.jsx("div",{className:"sticky left-0 w-[calc(100vw-30px)] max-w-[calc(100vw-30px)] md:w-full md:max-w-none box-border overflow-hidden px-3 sm:px-4 py-4 border-t border-border",children:S.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No orders for this customer."}):e.jsxs(e.Fragment,{children:[(()=>{var F;const x=((F=re==null?void 0:re.superInvoicesByCustomer)==null?void 0:F.get(t.id))??[];return x.length?e.jsx(Zt,{superInvoices:x,customer:{id:t.id,name:`${t.first_name??""} ${t.last_name??""}`.trim()||t.email||"Customer",email:t.email,phone:t.phone},addingToSuperId:is[t.id]??null,onCancelAdding:()=>{_e(t.id),Ie(Q=>{const B={...Q};return delete B[t.id],B})},onAddInvoices:Q=>{Ie(B=>({...B,[t.id]:Q})),_e(t.id),D.success('Select invoices below, then click "Add to consolidated"'),requestAnimationFrame(()=>{var B;(B=document.getElementById(`orders-anchor-${t.id}`))==null||B.scrollIntoView({behavior:"smooth",block:"start"})})}}):null})(),(()=>{var be;const x=is[t.id]??null,F=!!x,Q=F?1:2,B=W.length>=Q,q=((be=re==null?void 0:re.superInvoicesByCustomer)==null?void 0:be.get(t.id))??[],le=F?q.find(ne=>ne.id===x):null,ve=le!=null&&le.invoice_number?`#${le.invoice_number}`:"";return e.jsx("div",{id:`orders-anchor-${t.id}`,className:"scroll-mt-20",children:e.jsxs("div",{className:`mb-3 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 rounded-lg border px-3 py-2 transition-colors ${B?"border-primary/30 bg-primary/5":"border-dashed border-border bg-muted/20"}`,children:[e.jsxs("div",{className:"text-sm flex items-center gap-2",children:[e.jsx(ie,{className:`w-4 h-4 ${B?"text-primary":"text-muted-foreground"}`}),F?B?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"font-semibold",children:["Adding ",W.length," to ",ve||"consolidated invoice"]}),e.jsxs("span",{className:"text-muted-foreground",children:[" · +",a(je)]})]}):e.jsxs("span",{className:"text-muted-foreground",children:["Adding to ",e.jsx("span",{className:"font-mono font-semibold text-foreground",children:ve})," â select 1 or more ",e.jsx("span",{className:"text-foreground font-medium",children:"unpaid"})," invoices below."]}):B?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"font-semibold",children:[W.length," invoices selected"]}),e.jsxs("span",{className:"text-muted-foreground",children:[" · Total ",a(je)]})]}):e.jsxs("span",{className:"text-muted-foreground",children:["Select 2 or more ",e.jsx("span",{className:"text-foreground font-medium",children:"unpaid"})," invoices below to consolidate them into a single payment."]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[(B||F)&&e.jsx(k,{size:"sm",variant:"ghost",onClick:()=>{_e(t.id),F&&Ie(ne=>{const ue={...ne};return delete ue[t.id],ue})},children:F?"Cancel":"Clear"}),e.jsx(Ue,{delayDuration:150,children:e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("span",{tabIndex:0,children:e.jsxs(k,{size:"sm",className:"gap-1.5",disabled:!B||os.isPending,onClick:async()=>{if(B)if(F&&x)try{await os.mutateAsync({super_invoice_id:x,add_child_invoice_ids:W.map(ne=>ne.invoice_id)}),D.success(`Added ${W.length} invoice${W.length===1?"":"s"} to the consolidated invoice`),_e(t.id),Ie(ne=>{const ue={...ne};return delete ue[t.id],ue})}catch{}else ns(t.id)},children:[e.jsx(ie,{className:"w-3.5 h-3.5"}),F?`Add to ${ve||"consolidated invoice"}`:"Consolidate into Super Invoice"]})})}),e.jsx(Ke,{className:"max-w-xs",children:F?"Adds the selected invoices to the existing consolidated invoice. The total recalculates and the payment link refreshes automatically.":"Creates a single invoice summing all selected (including taxes, fees and extras). You can absorb the card fee, charge the saved card, or send a single PDF + payment link."})]})})]})]})})})(),e.jsx("div",{className:"hidden md:block overflow-x-auto rounded-lg border border-border bg-card",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/30",children:e.jsxs("tr",{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground",children:[e.jsx("th",{className:"px-2 py-2.5 w-[36px]"}),e.jsx("th",{className:"text-left px-4 py-2.5",children:"Order ID"}),e.jsx("th",{className:"text-left px-4 py-2.5",children:"Customer"}),e.jsx("th",{className:"text-left px-4 py-2.5",children:"Contracted"}),e.jsx("th",{className:"text-left px-4 py-2.5",children:"Expenses"}),e.jsx("th",{className:"text-left px-4 py-2.5",children:"P&L"}),e.jsx("th",{className:"text-left px-4 py-2.5",children:"Status"}),e.jsx("th",{className:"text-left px-4 py-2.5"})]})}),e.jsx("tbody",{children:S.map((x,F)=>{const Q=cs(x);return e.jsx(et,{order:x,isExpanded:ke===x.id,onToggle:()=>ts(ke===x.id?null:x.id),isEven:F%2===1,selectable:!0,selected:!!x._invoiceId&&R.has(x._invoiceId),selectDisabled:!Q.selectable,selectDisabledReason:Q.reason,onSelectChange:B=>x._invoiceId&&ds(t.id,x._invoiceId,B)},x.id)})})]})}),e.jsx("div",{className:"md:hidden space-y-2",children:S.map(x=>{const F=cs(x);return e.jsx(st,{order:x,isExpanded:ke===x.id,onToggle:()=>ts(ke===x.id?null:x.id),selectable:!0,selected:!!x._invoiceId&&R.has(x._invoiceId),selectDisabled:!F.selectable,selectDisabledReason:F.reason,onSelectChange:Q=>x._invoiceId&&ds(t.id,x._invoiceId,Q)},x.id)})})]})})})},`${t.id}-expanded`)})()]},t.id)}):e.jsx(Ce,{children:e.jsx(G,{colSpan:10,className:"py-16",children:e.jsxs("div",{className:"flex flex-col items-center text-center",children:[e.jsx("div",{className:"w-14 h-14 roun
3ded-2xl bg-muted flex items-center justify-center mb-4",children:e.jsx(ys,{className:"w-7 h-7 text-muted-foreground"})}),e.jsx("h3",{className:"text-base font-semibold text-foreground",children:r("customers.noCustomersFound")??"No customers found"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:r("customers.addFirstCustomer")??"Add your first customer"})]})})})})]}),e.jsx(xt,{currentPage:z,totalItems:pe.length,pageSize:O,onPageChange:H,onPageSizeChange:t=>{V(t),H(1)}})]}),e.jsx(rt,{open:C,onOpenChange:y,onSave:t=>{console.log("New customer:",t)}}),e.jsx(Bt,{open:se,onClose:()=>T(!1)}),N&&e.jsx(ct,{customer:N,onClose:()=>X(null)}),(()=>{if(!ge)return null;const t=p.find(S=>S.id===ge);if(!t)return null;const d=ls.get(ge)??[],E=rs[ge]??new Set,M=d.filter(S=>S._invoiceId&&E.has(S._invoiceId)).map(S=>{var me,ae;return{invoice_id:S._invoiceId,invoice_number:S._invoiceNumber??"â",order_id:S.id,total:Number(S._invoiceTotal??S.total??0),tax:Number(((me=S.paymentInfo)==null?void 0:me.salesTax)??0),fuel_surcharge:Number(((ae=S.paymentInfo)==null?void 0:ae.fuelSurcharge)??0),processing_fee:Number(S._invoiceProcessingFee??0),has_extras:(S.overweightAmount??0)>0||(S._extraCharges??[]).length>0}});return e.jsx(Kt,{open:!!ge,onOpenChange:S=>{S||(ns(null),_e(ge))},customer:{id:t.id,company_id:t.company_id,full_name:`${t.first_name??""} ${t.last_name??""}`.trim()||(t.company_name??"Customer"),email:t.email,phone:t.phone},children:M})})()]})}export{Wn 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.