1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/printReport-CsuYo3G5.js","assets/index-BDOD5E4V.js","assets/vendor-Dz9lJ0A9.js","assets/index-DOWM1KK1.css"])))=>i.map(i=>d[i]); 2import{an as ke,e as T,B as re,D as _,m as w,Q as H,ak as ue,P as X,a0 as he,a1 as ge,a2 as fe,a3 as je,K as Z,u as Ce,L as ye,af as be,E as Se,am as $e,aH as J,U as ve,_ as Ee,Z as Te,f as De,a9 as Re,X as Le}from"./index-BDOD5E4V.js";import{j as e,r as j}from"./vendor-Dz9lJ0A9.js";import Fe from"./purify.es-D7kaK67O.js";import{u as Pe}from"./use-debounced-value-BJebhLgm.js";import{c as B,a as Me}from"./PageSkeleton-Z6I6d4Km.js";import{P as Ae}from"./PageHelper-DlLkbNgT.js";import{I as q}from"./input-uKcRzRZU.js";import{S as O,a as V,b as G,c as Y,d as R}from"./select-BqpPFFZ7.js";import{a as U}from"./date-utils-VPArwFdR.js";import{c as p,S as y,f as K,p as I}from"./CrmUtils-DEwMBVc2.js";import{R as Ne}from"./receipt-Cce0V-be.js";import"./community-forum-Cz56orCo.js";import{E as Be,I as Ie}from"./constants-Hyk7busR.js";import{F as ne}from"./file-spreadsheet-CRVS43wl.js";import{S as qe}from"./settings-2-0Dw1bLtV.js";import{g as Ue}from"./preset-date-utils-Du-uonZs.js";import{e as le}from"./email-type-labels-BGKb08uz.js";import{S as _e}from"./search-_0AhvJvF.js";import{S as Oe}from"./send-D2ID-sFR.js";import{C as Ve}from"./circle-check-CJ_VUuj_.js";import{P as Ge}from"./printer-bDZ0QXy3.js";import{T as we}from"./trending-up-Dqc9y6QX.js";import{A as oe}from"./arrow-up-right-DB9QqAEC.js";import{C as Ye}from"./clock-BGjkcAN7.js";import{T as He}from"./target-20QkbUJ0.js";import{M as Ke}
2from"./map-pin-NOdPePnm.js";import{C as We}from"./chart-column-DVmyngU4.js";import"./skeleton-Dp0qviHj.js";import"./use-dismissed-hints-CS8gEuUL.js";import"./framer-motion-B-6Peltb.js";import"./circle-question-mark-Bqs4yPi3.js";import"./index-DiCFY80r.js";import"./index-DBElOBAj.js";import"./check-DtEZOD33.js";import"./chevron-up-Cxk5DR03.js";import"./camera-DNX3tEqr.js";import"./wine-BBVhHSxR.js";import"./party-popper-DEXQZVum.js";import"./gem-DEMHl1Fi.js";import"./image-CRRQUQpN.js";import"./calendar-Djt6tY64.js";import"./scroll-text-Cl-FGltI.js";import"./star-eyEMRSoI.js";import"./archive-8I_OaxNc.js";(function(){try{var s=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};s.SENTRY_RELEASE={id:"8dd115ac638cf6a2a2cf5668d0686c96509328ed"};var r=new s.Error().stack;r&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[r]="58372ff4-f777-4675-a0b3-95a0eab0022d",s._sentryDebugIdIdentifier="sentry-dbid-58372ff4-f777-4675-a0b3-95a0eab0022d")}catch{}})();const Qe=[["path",{d:"m7 7 10 10",key:"1fmybs"}],["path",{d:"M17 7v10H7",key:"6fjiku"}]],ee=ke("arrow-down-right",Qe);function ze({dates:s}){const r=new URLSearchParams;s.from&&r.set("from",s.from),s.to&&r.set("to",s.to);const l=r.toString()?`?${r.toString()}`:"",{data:n,isLoading:i}=T({queryKey:["/api/crm/reports/sales-tax",s.from,s.to],queryFn:async()=>{const t=await w("GET",`/api/crm/reports/sales-tax${l}`);if(!t.ok)throw new Error("Failed to fetch");return t.json()}});function a(){if(!n?.invoices?.length)return;const t=["Date","Invoice","Client","Status","Tax Rate %","Taxable Amount","Non-Taxable Amount","Tax Amount","Total"],o=n.invoices.map(m=>[U(m.date),m.title,m.clientName,m.status,(m.taxRate/100).toFixed(2),(m.taxableSubtotal/100).toFixed(2),(m.nonTaxableSubtotal/100).toFixed(2),(m.taxAmount/100).toFixed(2),(m.totalAmount/100).toFixed(2)]),c=[t.join(","),...o.map(m=>m.map(v=>`"${v}"`).join(","))].join(` 3`),u=new Blob([c],{type:"text/csv"}),h=URL.createObjectURL(u),x=document.createElement("a");x.href=h,x.download=`sales_tax_report${s.from?`_${s.from}`:""}${s.to?`_to_${s.to}`:""}.csv`,x.click(),URL.revokeObjectURL(h)}return i?e.jsx("div",{className:"space-y-4 animate-pulse","data-testid":"report-sales-tax-loading",children:[1,2,3].map(t=>e.jsx("div",{className:"h-20 bg-muted/40 rounded-lg"},t))}):!n||n.invoiceCount===0?e.jsxs("div",{className:"text-center py-16","data-testid":"report-sales-tax-empty",children:[e.jsx(Ne,{className:"w-10 h-10 mx-auto text-foreground/60 mb-3"}),e.jsx("p",{className:"text-sm text-foreground/70 italic",children:"No invoices with sales tax in this period"}),e.jsx("p",{className:"text-[11px] text-foreground/70 mt-1",children:"Set a sales tax rate on your invoices to see tax reporting here."})]}):e.jsxs("div",{className:"space-y-8","data-testid":"report-sales-tax",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4",children:[e.jsx("p",{className:"text-[10px] tracking-[0.15em] uppercase text-foreground/70 mb-1",children:"Tax Collected"}),e.jsx("p",{className:"text-xl font-display font-medium text-foreground/90","data-testid":"text-tax-collected",children:p(n.totalTaxCollected)}),e.jsx("p",{className:"text-[11px] text-foreground/70 mt-0.5",children:"Based on payments received"})]}),e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4",children:[e.jsx("p",{className:"text-[10px] tracking-[0.15em] uppercase text-foreground/70 mb-1",children:"Total Tax Charged"}),e.jsx("p",{className:"text-xl font-display font-medium text-foreground/90","data-testid":"text-tax-charged",children:p(n.totalTaxCharged)}),e.jsx("p",{className:"text-[11px] text-foreground/70 mt-0.5",children:"All statuses"})]}),e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4",children:[e.jsx("p",{className:"text-[10px] tracking-[0.15em] uppercase text-foreground/70 mb-1",children:"Taxable Revenue"}),e.jsx("p",{className:"text-xl font-display font-medium text-foreground/90","data-testid":"text-taxable-revenue",children:p(n.totalTaxableRevenue)})]}),e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4",children:[e.jsx("p",{className:"text-[10px] tracking-[0.15em] uppercase text-foreground
3/70 mb-1",children:"Non-Taxable"}),e.jsx("p",{className:"text-xl font-display font-medium text-foreground/90","data-testid":"text-nontaxable-revenue",children:p(n.totalNonTaxableRevenue)})]})]}),n.rateBreakdown?.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-[11px] tracking-[0.15em] uppercase text-foreground/70 mb-3",children:"By Tax Rate"}),e.jsx("div",{className:"space-y-2",children:n.rateBreakdown.map(t=>e.jsxs("div",{className:"flex items-center justify-between bg-muted/20 rounded-lg px-4 py-3",children:[e.jsxs("div",{children:[e.jsxs("span",{className:"text-sm font-display font-medium text-foreground/90",children:[(t.rate/100).toFixed(2),"%"]}),e.jsxs("span",{className:"text-[11px] text-foreground/70 ml-2",children:[t.count," invoice",t.count!==1?"s":""]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("span",{className:"text-sm font-display font-medium text-foreground/90",children:p(t.taxAmount)}),e.jsxs("span",{className:"text-[11px] text-foreground/70 ml-2",children:["on ",p(t.taxableAmount)]})]})]},t.rate))})]}),n.monthlyBreakdown?.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-[11px] tracking-[0.15em] uppercase text-foreground/70 mb-3",children:"Monthly Breakdown"}),e.jsx("div",{className:"space-y-1.5",children:n.monthlyBreakdown.map(t=>{const o=Math.max(...n.monthlyBreakdown.map(m=>m.taxAmount),1),c=t.taxAmount/o*100,[u,h]=t.month.split("-"),x=new Date(Number(u),Number(h)-1).toLocaleDateString("en-US",{month:"short",year:"numeric"});return e.jsxs("div",{className:"flex items-center gap-3 py-1.5",children:[e.jsx("div",{className:"w-20 text-[12px] text-foreground/65 font-display",children:x}),e.jsx("div",{className:"flex-1 h-6 bg-muted/20 rounded-sm overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-500/30 rounded-sm transition-all",style:{width:`${c}%`}})}),e.jsx("div",{className:"w-24 text-right text-[13px] font-display font-medium text-amber-600/70 dark:text-amber-400/70",children:p(t.taxAmount)}),e.jsxs("div",{className:"w-16 text-right text-[11px] text-foreground/70",children:[t.count," inv"]})]},t.month)})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-[11px] tracking-[0.15em] uppercase text-foreground/70",children:"Invoice Details"}),e.jsxs(re,{variant:"ghost",size:"sm",onClick:a,className:"text-[11px] h-7 text-foreground/65","data-testid":"button-export-tax-csv",children:[e.jsx(_,{className:"w-3 h-3 mr-1"}),"Export CSV"]})]}),e.jsx("div",{className:"border border-border/40 rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full text-[12px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/30 border-b border-border/30",children:[e.jsx("th",{className:"text-left py-2.5 px-3 text-[10px] tracking-[0.12em] uppercase text-foreground/70 font-medium",children:"Date"}),e.jsx("th",{className:"text-left py-2.5 px-3 text-[10px] tracking-[0.12em] uppercase text-foreground/70 font-medium",children:"Invoice"}),e.jsx("th",{className:"text-left py-2.5 px-3 text-[10px] tracking-[0.12em] uppercase text-foreground/70 font-medium",children:"Client"}),e.jsx("th",{className:"text-right py-2.5 px-3 text-[10px] tracking-[0.12em] uppercase text-foreground/70 font-medium",children:"Rate"}),e.jsx("th",{className:"text-right py-2.5 px-3 text-[10px] tracking-[0.12em] uppercase text-foreground/70 font-medium",children:"Taxable"}),e.jsx("th",{className:"text-right py-2.5 px-3 text-[10px] tracking-[0.12em] uppercase text-foreground/70 font-medium",children:"Tax"}),e.jsx("th",{className:"text-right py-2.5 px-3 text-[10px] tracking-[0.12em] uppercase text-foreground/70 font-medium",children:"Total"}),e.jsx("th",{className:"text-center py-2.5 px-3 text-[10px] tracking-[0.12em] uppercase text-foreground/70 font-medium",children:"Status"})]})}),e.jsx("tbody",{children:n.invoices.map(t=>e.jsxs("tr",{className:"border-b border-border/20 hover:bg-muted/15 transition-colors","data-testid":`row-tax-invoice-${t.id}`,children:[e.jsx("td",{className:"py-2 px-3 text-foreground/70",children:U(t.date)}
3),e.jsx("td",{className:"py-2 px-3 text-foreground/90 font-medium",children:t.title}),e.jsx("td",{className:"py-2 px-3 text-foreground/70",children:t.clientName}),e.jsxs("td",{className:"py-2 px-3 text-right text-foreground/70",children:[(t.taxRate/100).toFixed(2),"%"]}),e.jsx("td",{className:"py-2 px-3 text-right text-foreground/80",children:p(t.taxableSubtotal)}),e.jsx("td",{className:"py-2 px-3 text-right font-medium text-amber-600/80 dark:text-amber-400/80",children:p(t.taxAmount)}),e.jsx("td",{className:"py-2 px-3 text-right text-foreground/80",children:p(t.totalAmount)}),e.jsx("td",{className:"py-2 px-3 text-center",children:e.jsx("span",{className:`text-[10px] tracking-[0.1em] uppercase px-2 py-0.5 rounded-full ${t.status==="paid"?"bg-emerald-500/15 text-emerald-600 dark:text-emerald-400":t.status==="partial"?"bg-amber-500/15 text-amber-600 dark:text-amber-400":"bg-muted/40 text-foreground/60"}`,children:t.status})})]},t.id))})]})})]})]})}const ce={monthly:"Monthly",biweekly:"Every two weeks"};function Xe(){const s=new Date;return s.setDate(1),s.setMonth(s.getMonth()-1),`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}`}function Ze(){const s=new Date,r=Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()),l=Date.UTC(1970,0,12),n=1440*60*1e3,i=Math.floor((r-l)/(14*n))-1,a=new Date(l+i*14*n),t=new Date(a.getTime()+13*n);return{start:a.toISOString().slice(0,10),end:t.toISOString().slice(0,10)}}function Je(s){const r=new Date(`${s}T00:00:00.000Z`);return Number.isNaN(r.getTime())?"":(r.setUTCDate(r.getUTCDate()+13),r.toISOString().slice(0,10))}function et(s,r){const l=["Date","Transaction Type","Customer / Payee","Client","Event","Description","Account","Source Category","Mapping Status","Net Amount","Income","Expense","Service Income","Gratuity","Sales Tax","Payment Method","Source","Source Reference","Notes"],n=o=>`"${String(o??"").replace(/"/g,'""')}"`,i=[l.map(n).join(","),...r.map(o=>o.map(n).join(","))].join(` 4`),a=URL.createObjectURL(new Blob([i],{type:"text/csv;charset=utf-8;"})),t=document.createElement("a");t.href=a,t.download=s,t.click(),URL.revokeObjectURL(a)}function tt(){const{toast:s}=H(),r=ue(),[l,n]=j.useState("monthly"),[i,a]=j.useState(Xe),[t,o]=j.useState(()=>Ze().start),[c,u]=j.useState(!1),[h,x]=j.useState(!1),[m,v]=j.useState(!1),[b,F]=j.useState({income:{},expenses:{}}),{data:L}=T({queryKey:["/api/crm/settings"]});j.useEffect(()=>{const g=new URLSearchParams(r).get("month");g&&/^\d{4}-(0[1-9]|1[0-2])$/.test(g)&&(n("monthly"),a(g));const $=new URLSearchParams(r),k=$.get("start");$.get("cadence")==="biweekly"&&k&&/^\d{4}-\d{2}-\d{2}$/.test(k)&&(n("biweekly"),o(k))},[r]);const d=["Client Payments",...Ie],E=L?.customExpenseCategories&&L.customExpenseCategories.length>0?L.customExpenseCategories:[...Be],D=()=>{const g=L?.quickBooksCategoryMappings;F({income:Object.fromEntries(d.map($=>[$,g?.income?.[$]||($==="Client Payments"?"Photography Services":$)])),expenses:Object.fromEntries(E.map($=>[$,g?.expenses?.[$]||$]))}),x(!0)},N=async()=>{v(!0);try{if(!(await w("PATCH","/api/crm/reports/quickbooks-mappings",{mappings:b})).ok)throw new Error("Failed");await Z.refetchQueries({queryKey:["/api/crm/settings"]}),x(!1),s({title:"Account mapping saved"})}catch{s({title:"Could not save account mapping",variant:"destructive"})}finally{v(!1)}},S=async()=>{u(!0);try{const g=l==="biweekly"?`cadence=biweekly&start=${encodeURIComponent(t)}`:`cadence=monthly&month=${encodeURIComponent(i)}`,$=await w("GET",`/api/crm/reports/quickbooks-export?${g}`);if(!$.ok)throw new Error("Failed");const k=await $.json(),W={saved:"Saved mapping",default:"Using source category",needs_review:"Needs review"},te=k.transactions.map(C=>[C.date?C.date.slice(0,10):"",C.transactionType||"",C.name||"",C.client||"",C.event||"",C.description||"",C.quickBooksAccount||"",C.colaraCategory||"",W[C.mappingStatus]||C.mappingStatus||"",(C.amount/100).toFixed(2),(C.income/100).toFixed(2),(C.expense/100).toFixed(2),(C.serviceIncome/100).toFixed(2),(C.gratuity/100).toFixed(2),(C.salesTax/100).toFixed(2),C.paymentMethod||"",C.source||"",C.reference||"",C.notes||""]);et(`transactions_${k.cadence}_${k.from}_${k.to}.csv`,te),s({title:`${k.transactionCount} ${k.cadence==="biweekly"?"two-week":"monthly"} transactions exported`,description:k.needsReviewCount>0?`${k.needsReviewCount}
4 ${k.needsReviewCount===1?"row needs":"rows need"} an account review.`:"Every row has an account."})}catch{s({title:"Export failed",variant:"destructive"})}finally{u(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-lg border border-border/15 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{className:"w-4 h-4 text-foreground/70"}),e.jsx("h3",{className:"text-[15px] font-display font-light tracking-tight",children:"All transactions"})]}),e.jsxs(re,{variant:"outline",size:"sm",onClick:D,"data-testid":"button-manage-qb-mappings",children:[e.jsx(qe,{className:"w-3.5 h-3.5"}),"Account mapping"]})]}),e.jsx("p",{className:"text-[12px] text-foreground/65 leading-relaxed mb-4",children:"Export every payment, refund, manual income entry, and expense for one month or a two-week period. Each transaction stays on its own row and includes the matching account name from your account mapping."}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] tracking-[0.12em] uppercase text-foreground/60 mb-1",children:"Period"}),e.jsxs(O,{value:l,onValueChange:g=>n(g),children:[e.jsx(V,{className:"h-9 w-[170px] text-[12px]","data-testid":"select-quickbooks-export-cadence",children:e.jsx(G,{})}),e.jsx(Y,{children:Object.keys(ce).map(g=>e.jsx(R,{value:g,children:ce[g]},g))})]})]}),l==="monthly"?e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] tracking-[0.12em] uppercase text-foreground/60 mb-1",children:"Month"}),e.jsx(q,{type:"month",value:i,onChange:g=>a(g.target.value),className:"h-9 w-[160px] text-[12px]","data-testid":"input-quickbooks-month"})]}):e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] tracking-[0.12em] uppercase text-foreground/60 mb-1",children:"Period starts"}),e.jsx(q,{type:"date",value:t,onChange:g=>o(g.target.value),className:"h-9 w-[160px] text-[12px]","data-testid":"input-quickbooks-biweekly-start"}),e.jsxs("p",{className:"mt-1 text-[10px] text-foreground/50",children:["Through ",Je(t)]})]}),e.jsxs(X,{onClick:S,disabled:c||(l==="monthly"?!i:!t),"data-testid":"button-export-quickbooks-monthly",children:[e.jsx(_,{className:"w-3.5 h-3.5"}),c?"Exporting...":`Export ${l==="biweekly"?"two-week":"monthly"} CSV`]})]}),e.jsx("p",{className:"text-[11px] text-foreground/50 leading-relaxed mt-3",children:"The CSV is a bookkeeping handoff with signed amounts, separate income and expense columns, sales tax, gratuity, source, and a stable source reference for reconciliation."})]}),e.jsx(he,{open:h,onOpenChange:x,children:e.jsxs(ge,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsx(fe,{children:e.jsx(je,{children:"Account mapping"})}),e.jsx("p",{className:"text-[12px] text-foreground/65 leading-relaxed",children:"Enter account names exactly as they appear in your accounting software's chart of accounts. The CSV keeps the original category too, so every mapping can be audited."}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsx(de,{title:"Income",categories:d,values:b.income,onChange:(g,$)=>F(k=>({...k,income:{...k.income,[g]:$}}))}),e.jsx(de,{title:"Expenses",categories:E,values:b.expenses,onChange:(g,$)=>F(k=>({...k,expenses:{...k.expenses,[g]:$}}))})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(re,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx(X,{onClick:N,disabled:m,children:m?"Saving...":"Save mapping"})]})]})})]})}function de({title:s,categories:r,values:l,onChange:n}){return e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-[10px] tracking-[0.16em] uppercase text-foreground/60",children:s}),r.map(i=>e.jsxs("div",{children:[e.jsx("label",{className:"block text-[11px] text-foreground/65 mb-1",children:i}),e.jsx(q,{value:l[i]||"",onChange:a=>n(i,a.target.value),placeholder:"Account name",className:"h-9 text-[12px]"})]},i))]})}function st(){const{data:s,isLoading:r}=T({queryKey:["/api/crm/reports/proposal-conversion"],queryFn:async()=>{const a=await w("GET","/api/crm/reports/proposal-conversion");if(!a.ok)throw new Error("Failed");return a.json()}});if(r)return e.jsx(B,{className:"py-6"});if(!s)return null;const l=[{key:"sent",label:"Sent",count:s.funnel.sent,color:"bg-primary/30"},{key:"viewed",label:"Viewed",count:s.funnel.viewed,color:"bg-primary/45"},{key:"accepted",label:"Accepted",count:s.funnel.accepted,color:"bg-primary/60"}],n=Math.max(s.funnel.sent,1),i=s.proposals.filter(a=>a.sentAt||a.status!=="draft").slice(0,5);return e.jsxs("div",{"data-testid":"report-proposal-conversion",children:[e.jsx(y,{children:"Proposal Conversion"}),e.jsx("div",{className:"mt-5 space-y-2",children:l.map((a,t)=>{const o=a.count/n*100,c=s.funnel.sent>0?Math.round(a.count/s.funnel.sent*100):0,u=t>0?l[t-1].count:0,h=t>0&&u>0?Math.round((1-a.count/u)*100):0;return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`proposal-funnel-${a.key}`,children:[e.jsx("div",{className:"w-28 text-xs font-medium",children:a.label}),e.jsx("div",{className:"flex-1 flex items-center",children:e.jsx("div",{className:"relative w-full",children:e.jsx("div",{className:"h-8 bg-muted/10 rounded-sm overflow-hidden",style:{width:"100%"},children:e.jsx("div",{className:`h-full ${a.color} rounded-sm transition-all duration-500 flex items-center`,style:{width:`${Math.max(o,3)}%`},children:e.jsx("span",{className:"text-[11px] font-medium ml-2 whitespace-nowrap",children:a.count})})})})}),e.jsxs("div",{className:"w-16 text-right text-[11px] text-foreground
4/65",children:[c,"%"]}),t>0&&h>0?e.jsxs("div",{className:"w-20 text-right text-[10px] text-red-400/70",children:["-",h,"% drop"]}):e.jsx("div",{className:"w-20"})]},a.key)})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-y-3 mt-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.1em] text-foreground/60",children:"Avg Days to View"}),e.jsx("div",{className:"text-sm font-medium mt-0.5",children:s.avgDaysToView??"â"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.1em] text-foreground/60",children:"Avg Days to Accept"}),e.jsx("div",{className:"text-sm font-medium mt-0.5",children:s.avgDaysToAccept??"â"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.1em] text-foreground/60",children:"Accepted Value"}),e.jsx("div",{className:"text-sm font-medium mt-0.5",children:p(s.acceptedValue)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.1em] text-foreground/60",children:"Awaiting Response"}),e.jsxs("div",{className:"text-sm font-medium mt-0.5",children:[s.funnel.awaiting," · ",p(s.awaitingValue)]})]})]}),i.length>0&&e.jsx("div",{className:"mt-5 space-y-1.5","data-testid":"proposal-conversion-recent",children:i.map(a=>e.jsxs("div",{className:"flex items-center gap-3 text-[11px]",children:[e.jsxs("div",{className:"flex-1 min-w-0 truncate",children:[e.jsx("span",{className:"font-medium",children:a.title}),a.contactName&&e.jsxs("span",{className:"text-foreground/60",children:[" · ",a.contactName]})]}),e.jsx("div",{className:"w-24 text-foreground/65 text-right",children:a.sentAt?`Sent ${K(a.sentAt)}`:""}),e.jsx("div",{className:"w-32 text-right",children:a.status==="accepted"?e.jsx("span",{className:"text-emerald-600/80 dark:text-emerald-400/80",children:"Accepted"}):a.status==="declined"?e.jsx("span",{className:"text-red-500/70",children:"Declined"}):a.viewedAt?e.jsxs("span",{className:"text-foreground/70",children:["Viewed",a.viewCount>1?` Ã${a.viewCount}`:""]}):e.jsx("span",{className:"text-foreground/50 italic",children:"Not opened yet"})})]},a.id))}),s.funnel.sent===0&&e.jsx("p",{className:"text-[11px] text-foreground/65 mt-4 italic",children:"Send your first proposal to see how quickly clients open and accept them."})]})}const at=["profit-loss","income","expenses","client-profitability","receivables","pipeline","lead-sources","sales-tax","tax-export","analytics"];function xe(s){const r=new URLSearchParams(s).get("report");return r&&at.includes(r)?r:null}function rt(){const s=ue(),[,r]=Ce(),[l,n]=j.useState(()=>xe(s)||"profit-loss");return j.useEffect(()=>{const a=xe(s);a&&n(a)},[s]),{reportType:l,selectReportType:a=>{n(a);const t=new URLSearchParams(s);t.set("report",a),r(`/crm?${t.toString()}`)}}}function nt({dates:s}){const r=new URLSearchParams;s.from&&r.set("from",s.from),s.to&&r.set("to",s.to);const l=r.size?`?${r.toString()}`:"",{data:n,isLoading:i}=T({queryKey:["/api/crm/reports/client-profitability",s.from,s.to],queryFn:async()=>{const a=await w("GET",`/api/crm/reports/client-profitability${l}`);if(!a.ok)throw new Error("Failed to load client profitability");return a.json()}});return i?e.jsx(B,{className:"py-6"}):n?e.jsxs("div",{className:"space-y-8","data-testid":"report-client-profitability",children:[e.jsxs("div",{className:"flex items-stretch",children:[e.jsx(Q,{label:"Collected",value:n.totalCollectedRevenue}),e.jsx(se,{}),e.jsx(Q,{label:"Direct Expenses",value:n.totalDirectExpenses}),e.jsx(se,{}),e.jsx(Q,{label:"Client/Event Net",value:n.totalNetProfit}),e.jsx(se,{}),e.jsx(Q,{label:"Business Overhead",value:n.unassignedExpenses})]}),e.jsxs("div",{className:"rounded-md border border-border/15 bg-muted/10 px-4 py-3 text-[11px] text-foreground/65 leading-relaxed",children:["Direct expenses are counted only against the client or event you selected. General business overhead remains separate and is never distributed across clients. Net after overhead is"," ",e.jsx("span",{className:"font-medium text-foreground",children:p(n.netAfterOverhead)}),". The selected date range applies to invoice creation, payment, manual income, and expense dates."]}),n.rows.length?e.jsx("div",{className:"overflow-x-auto border-t border-border/12 pt-6",children:e.jsxs("table",{className:"w-full min-w-[920px] text-left",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] tracking-[0.14em] uppercase text-foreground
4/55 border-b border-border/15",children:[e.jsx("th",{className:"py-3 pr-4 font-medium",children:"Client / Event"}),e.jsx("th",{className:"py-3 px-3 text-right font-medium",children:"Contracted"}),e.jsx("th",{className:"py-3 px-3 text-right font-medium",children:"Collected"}),e.jsx("th",{className:"py-3 px-3 text-right font-medium",children:"Expenses"}),e.jsx("th",{className:"py-3 px-3 text-right font-medium",children:"Net"}),e.jsx("th",{className:"py-3 px-3 text-right font-medium",children:"Margin"}),e.jsx("th",{className:"py-3 pl-3 text-right font-medium",children:"Outstanding"})]})}),e.jsx("tbody",{children:n.rows.map(a=>e.jsxs("tr",{className:"border-b border-border/10 last:border-0","data-testid":`profit-row-${a.key}`,children:[e.jsxs("td",{className:"py-4 pr-4",children:[e.jsx("a",{href:`/clients/${a.contactId}?tab=expenses`,className:"text-[13px] font-medium hover:text-primary transition-colors",children:a.clientName}),e.jsxs("p",{className:"text-[10px] text-foreground/55 mt-1",children:[a.eventName||"Client-level",a.eventDate?` · ${K(a.eventDate)}`:"",a.expenseCount?` · ${a.expenseCount} expense${a.expenseCount===1?"":"s"}`:""]})]}),e.jsx(z,{amount:a.contractedRevenue}),e.jsx(z,{amount:a.collectedRevenue}),e.jsx(z,{amount:a.directExpenses,className:"text-red-500/80"}),e.jsx(z,{amount:a.netProfit,className:`font-medium ${a.netProfit>=0?"text-emerald-600":"text-red-500"}`}),e.jsxs("td",{className:"py-4 px-3 text-right text-[12px]",children:[a.profitMargin.toFixed(1),"%"]}),e.jsx("td",{className:"py-4 pl-3 text-right text-[12px]",children:p(a.outstandingRevenue)})]},a.key))})]})}):e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-sm text-foreground/70 italic",children:"No linked client or event activity in this period"}),e.jsx("p",{className:"text-[11px] text-foreground/55 mt-1",children:"Assign expenses to a client or event to see profitability here."})]})]}):null}function Q({label:s,value:r}){return e.jsxs("div",{className:"relative flex-1 text-center py-6",children:[e.jsx("p",{className:"text-2xl sm:text-3xl font-extralight tracking-tight font-display",children:p(r)}),e.jsx("p",{className:"text-[10px] tracking-[0.25em] uppercase text-foreground/65 mt-3 font-medium",children:s})]})}function se(){return e.jsx("div",{className:"w-px bg-border/8 my-4"})}function z({amount:s,className:r=""}){return e.jsx("td",{className:`py-4 px-3 text-right text-[12px] ${r}`,children:p(s)})}function ot(s,r,l){const n=["Client","Event","Event Date","Contracted Revenue","Collected Revenue","Direct Expenses","Net Profit","Profit Margin %","Outstanding Revenue","Expense Count"],i=(s.rows||[]).map(a=>[a.clientName,a.eventName||"Client-level",a.eventDate||"",M(a.contractedRevenue),M(a.collectedRevenue),M(a.directExpenses),M(a.netProfit),Number(a.profitMargin||0).toFixed(2),M(a.outstandingRevenue),String(a.expenseCount||0)]);i.push(["","","","","","","","","",""]),i.push(["TOTAL","","",M(s.totalContractedRevenue),M(s.totalCollectedRevenue),M(s.totalDirectExpenses),M(s.totalNetProfit),"",M(s.totalOutstandingRevenue),""]),i.push(["Business overhead","Not allocated","","","",M(s.unassignedExpenses),M(s.netAfterOverhead),"","",""]),l(`client_event_profitability${r}.csv`,n,i)}function M(s){return(Number(s||0)/100).toFixed(2)}const P={strong:"bg-primary/50",base:"bg-primary/40",soft:"bg-primary/25",faint:"bg-primary/15",neutral:"bg-muted/40"},me=["bg-primary/60","bg-primary/50","bg-primary/40","bg-primary/30","bg-primary/25","bg-primary/20"];function it(s){return me[Math.min(s,me.length-1)]}function lt({preset:s,setPreset:r,customFrom:l,setCustomFrom:n,customTo:i,setCustomTo:a}){return e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(O,{value:s,onValueChange:t=>r(t),children:[e.jsx(V,{className:"w-40 h-8 bg-muted/40 border-0 text-[13px]","data-testid":"select-date-preset",children:e.jsx(G,{})}),e.jsxs(Y,{children:[e.jsx(R,{value:"all",children:"All Time"}),e.jsx(R,{value:"ytd",children:"Year to Date"}),e.jsx(R,{value:"mtd",children:"Month to Date"}),e.jsx(R,{value:"last_month",children:"Last Month"}),e.jsx(R,{value:"last_quarter",children:"Last Quarter"}),e.jsx(R,{value:"last_year",children:"Last Year"}),e.jsx(R,{value:"custom",children:"Custom Range"})]})]}),s==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx(q,{type:"date",value:l,onCh
4ange:t=>n(t.target.value),className:"h-8 w-36 bg-muted/40 border-0 text-[13px]","data-testid":"input-date-from"}),e.jsx("span",{className:"text-[12px] text-foreground/65",children:"to"}),e.jsx(q,{type:"date",value:i,onChange:t=>a(t.target.value),className:"h-8 w-36 bg-muted/40 border-0 text-[13px]","data-testid":"input-date-to"})]})]})}function A(s,r,l){const n=c=>`"${String(c??"").replace(/"/g,'""')}"`,i=[r.map(n).join(","),...l.map(c=>c.map(n).join(","))].join(` 5`),a=new Blob([i],{type:"text/csv;charset=utf-8;"}),t=URL.createObjectURL(a),o=document.createElement("a");o.href=t,o.download=s,o.click(),URL.revokeObjectURL(t)}function ct(s,r,l){const n=l.from&&l.to?`_${l.from}_to_${l.to}`:l.from?`_from_${l.from}`:"";if(s==="profit-loss"&&r){const i=["Month","Income","Expenses","Net Profit"],a=(r.monthlyBreakdown||[]).map(t=>[t.month,(t.income/100).toFixed(2),(t.expenses/100).toFixed(2),(t.net/100).toFixed(2)]);a.push(["","","",""]),a.push(["TOTAL",(r.totalIncome/100).toFixed(2),(r.totalExpenses/100).toFixed(2),(r.netProfit/100).toFixed(2)]),r.expenseCategoryBreakdown?.length&&(a.push(["","","",""]),a.push(["Expense Category","Amount","",""]),r.expenseCategoryBreakdown.forEach(t=>a.push([t.category,(t.amount/100).toFixed(2),"",""]))),r.incomeByClientBreakdown?.length&&(a.push(["","","",""]),a.push(["Income by Contact","Amount","",""]),r.incomeByClientBreakdown.forEach(t=>a.push([t.client,(t.amount/100).toFixed(2),"",""]))),A(`profit_loss${n}.csv`,i,a)}if(s==="income"&&r){const i=["Date","Invoice","Client","Amount"],a=(r.payments||[]).map(t=>[t.date?U(t.date):"",t.title,t.clientName,(t.amount/100).toFixed(2)]);a.push(["","","",""]),a.push(["","","TOTAL",(r.totalCollected/100).toFixed(2)]),A(`income_report${n}.csv`,i,a)}if(s==="expenses"&&r){const i=["Date","Vendor","Category","Client","Event","Amount","Tax Deductible"],a=(r.recentExpenses||[]).map(t=>[t.date?U(t.date):"",t.payee,t.category,t.clientName||"Business overhead",t.eventName||(t.clientName?"Client-level":""),(t.amount/100).toFixed(2),t.taxDeductible?"Yes":"No"]);a.push(["","","","","","",""]),a.push(["","","","","TOTAL",(r.totalExpenses/100).toFixed(2),""]),a.push(["","","","","Tax Deductible",(r.taxDeductibleTotal/100).toFixed(2),""]),A(`expense_report${n}.csv`,i,a)}if(s==="client-profitability"&&r&&ot(r,n,A),s==="receivables"&&r){const i=["Invoice","Client","Due Date","Status","Amount Outstanding","Category"],a=[];[{key:"pdOver90",label:"Past Due 90+"},{key:"pd90",label:"Past Due 61-90 Days"},{key:"pd60",label:"Past Due 31-60 Days"},{key:"pd30",label:"Past Due 1-30 Days"},{key:"dueToday",label:"Due Today"},{key:"next30",label:"Due in 1-30 Days"},{key:"next60",label:"Due in 31-60 Days"},{key:"next90",label:"Due in 61-90 Days"},{key:"beyond90",label:"Due in 90+ Days"},{key:"noDueDate",label:"No Due Date"}].forEach(o=>{(r.aged[o.key]||[]).forEach(c=>{a.push([c.title,c.clientName,c.dueDate?U(c.dueDate):"Not set",c.daysOverdue>0?`${c.daysOverdue}d overdue`:c.daysUntilDue>0?`Due in ${c.daysUntilDue}d`:"Due today",(c.remaining/100).toFixed(2),o.label])})}),a.push(["","","","","",""]),a.push(["","","","PAST DUE",(r.totalPastDue/100).toFixed(2),""]),a.push(["","","","UPCOMING",(r.totalUpcoming/100).toFixed(2),""]),a.push(["","","","TOTAL",(r.totalOutstanding/100).toFixed(2),""]),A("accounts_receivable.csv",i,a)}if(s==="pipeline"&&r){const i=["Stage","Contacts","Value"],a={lead:"Lead",proposal_sent:"Proposal Sent",booked:"Booked",completed:"Completed",archive:"Archive"},t=["lead","proposal_sent","booked","completed","archive"].map(o=>{const c=r.stages[o]||{count:0,value:0};return[a[o],String(c.count),(c.value/100).toFixed(2)]});t.push(["","",""]),t.push(["Total Contacts",String(r.totalContacts),""]),t.push(["Pipeline Value","",(r.totalPipelineValue/100).toFixed(2)]),t.push(["Booked Value","",(r.bookedValue/100).toFixed(2)]),t.push(["Conversion Rate",`${r.conversionRate}%`,""]),r.sourceBreakdown?.length&&(t.push(["","",""]),t.push(["Lead Source","Count",""]),r.sourceBreakdown.forEach(o=>t.push([o.source,String(o.count),""]))),A("sales_pipeline.csv",i,t)}
5if(s==="lead-sources"&&r){const i=["Source","Leads","Share %","Booked","Conversion %","Revenue"],a=(r.sources||[]).map(t=>[t.source,String(t.count),r.totalLeads>0?`${Math.round(t.count/r.totalLeads*100)}%`:"0%",String(t.booked),`${t.conversionRate}%`,(t.revenue/100).toFixed(2)]);a.push(["","","","","",""]),a.push(["TOTAL",String(r.totalLeads),r.totalLeads>0?"100%":"0%",String(r.totalBooked),"",""]),A(`lead_sources${n}.csv`,i,a)}if(s==="sales-tax"&&r){const i=["Date","Invoice","Client","Status","Tax Rate %","Taxable Amount","Non-Taxable Amount","Tax Amount","Total"],a=(r.invoices||[]).map(t=>[t.date?U(t.date):"",t.title,t.clientName,t.status,(t.taxRate/100).toFixed(2),(t.taxableSubtotal/100).toFixed(2),(t.nonTaxableSubtotal/100).toFixed(2),(t.taxAmount/100).toFixed(2),(t.totalAmount/100).toFixed(2)]);a.push(["","","","","","","","",""]),a.push(["","","","","","Taxable Revenue",(r.totalTaxableRevenue/100).toFixed(2),"Tax Collected",(r.totalTaxCollected/100).toFixed(2)]),A(`sales_tax_report${n}.csv`,i,a)}}function f({label:s,value:r,sub:l}){return e.jsxs("div",{className:"relative flex-1 text-center py-6",children:[e.jsx("p",{className:"text-2xl sm:text-3xl font-extralight tracking-tight font-display","data-testid":`text-stat-${s.toLowerCase().replace(/\s/g,"-")}`,children:r}),e.jsx("p",{className:"text-[12px] tracking-[0.25em] uppercase text-foreground/65 mt-3 font-medium",children:s}),l&&e.jsx("p",{className:"text-[12px] text-foreground/65 mt-1",children:l})]})}function ae({value:s,label:r}){if(s===0)return null;const l=s>0,n=l?oe:ee;return e.jsxs("span",{className:`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[12px] font-medium tracking-wide ${l?"bg-emerald-50 text-emerald-700 dark:bg-emerald-900/20 dark:text-emerald-400":"bg-red-50 text-red-700 dark:bg-red-900/20 dark:text-red-400"}`,"data-testid":`badge-yoy-${r||"change"}`,children:[e.jsx(n,{className:"w-3 h-3"}),l?"+":"",s,"% vs prior year"]})}function ie({dates:s,reportType:r}){const[l,n]=j.useState(!1),i=new URLSearchParams;s.from&&i.set("from",s.from),s.to&&i.set("to",s.to),i.set("type",r);const a=i.toString()?`?${i.toString()}`:"",{data:t,isLoading:o,isError:c}=T({queryKey:["/api/crm/reports/yoy-comparison",s.from,s.to,r],queryFn:async()=>{const u=await w("GET",`/api/crm/reports/yoy-comparison${a}`);if(!u.ok)throw new Error("Failed");return u.json()},enabled:l,retry:1});return e.jsxs("div",{className:"pt-6 border-t border-border/12","data-testid":"panel-yoy-comparison",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx(y,{children:"Year-over-Year Comparison"}),e.jsxs("button",{onClick:()=>n(!l),className:`flex items-center gap-1.5 px-3 py-1.5 text-[12px] tracking-[0.12em] uppercase font-medium rounded border transition-colors ${l?"bg-primary/10 text-primary border-primary/20":"text-foreground/70 border-border/15 hover:text-foreground hover:border-border/30"}`,"data-testid":"button-toggle-yoy",children:[e.jsx(Te,{className:"w-3 h-3"}),l?"Hide YoY":"Compare to Last Year"]})]}),l&&o&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ye,{className:"w-5 h-5 animate-spin text-primary"})}),l&&c&&e.jsxs("div",{className:"text-center py-6",children:[e.jsx(J,{className:"w-5 h-5 text-red-700 dark:text-red-400 mx-auto mb-2"}),e.jsx("p",{className:"text-[12px] text-foreground/70",children:"Unable to load year-over-year comparison"})]}),l&&t&&!t.message&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3 text-[12px] tracking-[0.15em] uppercase text-foreground/70",children:[e.jsx("span",{className:"px-2 py-1 bg-primary/8 rounded",children:t.periodLabel?.current||"Current"}),e.jsx("span",{children:"vs"}),e.jsx("span",{className:"px-2 py-1 bg-muted/30 rounded",children:t.periodLabel?.prior||"Prior"})]}),(r==="profit-loss"||r==="income")&&t.changes&&e.jsxs("div",{className:"flex items-stretch border border-border/8 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex-1 text-center py-4 px-2",children:[e.jsx("p",{className:"text-lg font-display font-light",children:p(t.current?.totalIncome||0)}),e.jsx("p",{className:"text-[11px] tracking-[0.2em] uppercase text-foreground
5/70 mt-1",children:"Current Income"}),e.jsx("div",{className:"mt-2",children:e.jsx(ae,{value:t.changes.income,label:"income"})})]}),e.jsx("div",{className:"w-px bg-border/8"}),e.jsxs("div",{className:"flex-1 text-center py-4 px-2",children:[e.jsx("p",{className:"text-lg font-display font-light text-foreground/70",children:p(t.prior?.totalIncome||0)}),e.jsx("p",{className:"text-[11px] tracking-[0.2em] uppercase text-foreground/70 mt-1",children:"Prior Income"})]}),r==="profit-loss"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px bg-border/8"}),e.jsxs("div",{className:"flex-1 text-center py-4 px-2",children:[e.jsx("p",{className:"text-lg font-display font-light",children:p(t.current?.netProfit||0)}),e.jsx("p",{className:"text-[11px] tracking-[0.2em] uppercase text-foreground/70 mt-1",children:"Current Net"}),e.jsx("div",{className:"mt-2",children:e.jsx(ae,{value:t.changes.netProfit,label:"net"})})]}),e.jsx("div",{className:"w-px bg-border/8"}),e.jsxs("div",{className:"flex-1 text-center py-4 px-2",children:[e.jsx("p",{className:"text-lg font-display font-light text-foreground/70",children:p(t.prior?.netProfit||0)}),e.jsx("p",{className:"text-[11px] tracking-[0.2em] uppercase text-foreground/70 mt-1",children:"Prior Net"})]})]})]}),r==="lead-sources"&&t.sourceComparison&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-4 text-[12px] tracking-[0.15em] uppercase text-foreground/70 mb-3 px-1",children:[e.jsx("div",{className:"w-32",children:"Source"}),e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:"w-16 text-right",children:t.periodLabel?.current}),e.jsx("div",{className:"w-16 text-right",children:t.periodLabel?.prior}),e.jsx("div",{className:"w-20 text-right",children:"Change"})]}),t.sourceComparison.slice(0,10).map(u=>e.jsxs("div",{className:"flex items-center gap-4 py-2 border-b border-border/6 px-1","data-testid":`yoy-source-${u.source}`,children:[e.jsx("div",{className:"w-32 text-xs truncate",children:u.source}),e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:"w-20 text-right text-[14px] font-display",children:u.current}),e.jsx("div",{className:"w-20 text-right text-[14px] font-display text-foreground/70",children:u.prior}),e.jsx("div",{className:"w-20 text-right",children:e.jsx(ae,{value:u.change,label:u.source})})]},u.source))]})]})]})}function dt(){const{data:s,isLoading:r,isError:l}=T({queryKey:["/api/crm/reports/busiest-months"],queryFn:async()=>{const t=await w("GET","/api/crm/reports/busiest-months");if(!t.ok)throw new Error("Failed");return t.json()},retry:1});if(r)return e.jsx(Me,{rows:3,className:"py-4"});if(l)return e.jsxs("div",{className:"text-center py-6",children:[e.jsx(J,{className:"w-5 h-5 text-red-700 dark:text-red-400 mx-auto mb-2"}),e.jsx("p",{className:"text-[12px] text-foreground/70",children:"Unable to load busiest months data"})]});if(!s||!s.heatmap||s.totalBookings===0)return null;const n=Math.max(...s.heatmap.map(t=>t.total),1),i=["bg-primary/5","bg-primary/12","bg-primary/20","bg-primary/30","bg-primary/45","bg-primary/60"];function a(t){if(t===0)return"bg-muted/10";const o=Math.min(Math.ceil(t/n*5),5);return i[o]}return e.jsxs("div",{"data-testid":"chart-busiest-months",children:[e.jsx(y,{children:"Busiest Months"}),e.jsxs("p",{className:"text-[12px] text-foreground/70 mt-1 mb-5",children:["Booking volume by month â peak: ",e.jsx("strong",{children:s.peakMonth})," (",s.peakCount," bookings)"]}),e.jsx("div",{className:"grid grid-cols-12 gap-1.5 mb-4",children:s.heatmap.map(t=>e.jsxs("div",{className:`rounded-md py-4 text-center transition-colors ${a(t.total)}`,title:`${t.month}: ${t.total} bookings`,"data-testid":`busiest-month-${t.month}`,children:[e.jsx("p",{className:"text-[12px] tracking-[0.1em] uppercase text-foreground/70 font-medium",children:t.month}),e.jsx("p",{className:"text-lg font-display font-light mt-1",children:t.total})]},t.month))}),s.years.length>1&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"text-[12px] tracking-[0.15em] uppercase text-foreground/70 mb-2",children:"By Year"}),e.jsx("div",{className:"space-y-1.5",children:s.years.map(t=>{const o=s.heatmap.reduce((u,h)=>u+(h.byYear[t]||0),0),c=Math.max(...s.heatmap.map(u=>u.byYear[t]||0),1);return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`busiest-year-${t}`,children:[e.jsx("div",{className:"w-12 text-xs font-medium text-foreground
5/70",children:t}),e.jsx("div",{className:"flex-1 flex gap-0.5",children:s.heatmap.map(u=>{const h=u.byYear[t]||0,x=h>0?Math.max(6,Math.round(h/c*28)):3;return e.jsx("div",{className:"flex-1 flex items-end justify-center",style:{height:32},title:`${u.month} ${t}: ${h}`,children:e.jsx("div",{className:`w-full rounded-t-sm ${h>0?"bg-primary/30":"bg-muted/10"}`,style:{height:x}})},u.month)})}),e.jsx("div",{className:"w-12 text-right text-[13px] text-foreground/70",children:o})]},t)})})]})]})}function xt({dates:s}){const r=new URLSearchParams;s.from&&r.set("from",s.from),s.to&&r.set("to",s.to);const l=r.toString()?`?${r.toString()}`:"",{data:n,isLoading:i}=T({queryKey:["/api/crm/reports/profit-loss",s.from,s.to],queryFn:async()=>{const t=await w("GET",`/api/crm/reports/profit-loss${l}`);if(!t.ok)throw new Error("Failed");return t.json()}});if(i)return e.jsx(B,{className:"py-6"});if(!n)return null;const a=Math.max(...(n.monthlyBreakdown||[]).map(t=>Math.max(t.income,t.expenses)),1);return e.jsxs("div",{className:"space-y-8","data-testid":"report-profit-loss",children:[e.jsxs("div",{className:"flex items-stretch","data-testid":"pl-stats",children:[e.jsx(f,{label:"Total Income",value:p(n.totalIncome),sub:n.totalRefunds>0?`${p(n.grossIncome)} gross â ${p(n.totalRefunds)} refunds`:void 0}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Total Expenses",value:p(n.totalExpenses)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Net Profit",value:p(n.netProfit),sub:n.profitMargin>0?`${n.profitMargin}% margin`:void 0})]}),n.monthlyBreakdown&&n.monthlyBreakdown.length>0&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Monthly Profit & Loss"}),e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-4 text-[12px] tracking-[0.2em] uppercase text-foreground/70 mb-3",children:[e.jsx("div",{className:"w-20",children:"Month"}),e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:"w-28 text-right",children:"Income"}),e.jsx("div",{className:"w-28 text-right",children:"Expenses"}),e.jsx("div",{className:"w-28 text-right",children:"Net"})]}),n.monthlyBreakdown.map(t=>{const o=I(t.month+"-01").toLocaleDateString("en-US",{month:"short",year:"numeric"}),c=a>0?t.income/a*100:0,u=a>0?t.expenses/a*100:0;return e.jsxs("div",{className:"flex items-center gap-4","data-testid":`pl-row-${t.month}`,children:[e.jsx("div",{className:"w-20 text-xs font-medium",children:o}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("div",{className:"h-1 bg-muted/15 rounded-sm overflow-hidden",children:e.jsx("div",{className:`h-full ${P.strong} rounded-sm transition-all`,style:{width:`${c}%`}})}),e.jsx("div",{className:"h-1 bg-muted/15 rounded-sm overflow-hidden",children:e.jsx("div",{className:`h-full ${P.faint} rounded-sm transition-all`,style:{width:`${u}%`}})})]}),e.jsx("div",{className:"w-28 text-right text-[14px] font-display font-medium text-emerald-700 dark:text-emerald-400",children:p(t.income)}),e.jsx("div",{className:"w-28 text-right text-[14px] font-display text-red-700 dark:text-red-400",children:p(t.expenses)}),e.jsx("div",{className:`w-28 text-right text-[14px] font-display font-medium ${t.net>=0?"":"text-red-700 dark:text-red-400"}`,children:p(t.net)})]},t.month)})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:[n.expenseCategoryBreakdown&&n.expenseCategoryBreakdown.length>0&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Expenses by Category"}),e.jsx("div",{className:"mt-4 space-y-2",children:n.expenseCategoryBreakdown.map(t=>{const o=n.totalExpenses>0?t.amount/n.totalExpenses*100:0;return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`pl-cat-${t.category}`,children:[e.jsx("div",{className:"w-32 text-xs truncate",children:t.category}),e.jsx("div",{className:"flex-1 h-1 bg-muted/15 rounded-sm overflow-hidden",children:e.jsx("div",{className:`h-full ${P.soft} rounded-sm`,style:{width:`${o}%`}})}),e.jsx("div",{className:"w-28 text-right text-[14px] font-display",children:p(t.amount)})]},t.category)})})]}),n.incomeByClientBreakdown&&n.incomeByClientBreakdown.length>0&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Income by Contact"}),e.jsx("div",{className:"mt-4 space-y-2",children:(()=>{const t=Math.max(...n.incomeByClientBreakdown.map(o=>o.amount),1);return n.incomeByClientBreakdown.map(o=>{const c=o.amount/t*100;return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`pl-client-${o.client}`,children:[e.jsx("div",{className:"w-32 text-xs truncate",children:o.client}),e.jsx("div",{className:"flex-1 h-1 bg-muted/15 rounded-sm overflow-hidden",children:e.jsx("div",{className:`h-full ${P.base} rounded-sm`,style:{width:`${c}%`}})}),e.jsx("div",{className:"w-28 text-right text-[14px] font-display",children:p(o.amount)})]},o.client)})})()})]})]}),e.jsx(ie,{dates:s,reportType:"profit-loss"}),n.transactionCount===0&&e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-sm text-foreground
5/70 italic",children:"No transactions in this period"}),e.jsx("p",{className:"text-[12px] text-foreground/65 mt-1",children:"Record income through invoices and log expenses to see your P&L."})]})]})}function mt({dates:s}){const r=new URLSearchParams;s.from&&r.set("from",s.from),s.to&&r.set("to",s.to);const l=r.toString()?`?${r.toString()}`:"",{data:n,isLoading:i}=T({queryKey:["/api/crm/reports/income",s.from,s.to],queryFn:async()=>{const t=await w("GET",`/api/crm/reports/income${l}`);if(!t.ok)throw new Error("Failed");return t.json()}});if(i)return e.jsx(B,{className:"py-6"});if(!n)return null;const a=Math.max(...(n.monthlyBreakdown||[]).map(t=>t.collected),1);return e.jsxs("div",{className:"space-y-8","data-testid":"report-income",children:[e.jsxs("div",{className:"flex items-stretch",children:[e.jsx(f,{label:"Total Collected",value:p(n.totalCollected),sub:n.totalRefunds>0?`After ${p(n.totalRefunds)} in refunds`:void 0}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Payments",value:String(n.paymentCount)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Avg Payment",value:p(n.avgPayment)})]}),n.monthlyBreakdown&&n.monthlyBreakdown.length>0&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Monthly Income"}),e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-4 text-[12px] tracking-[0.2em] uppercase text-foreground/70 mb-3",children:[e.jsx("div",{className:"w-20",children:"Month"}),e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:"w-20 text-right",children:"Payments"}),e.jsx("div",{className:"w-32 text-right",children:"Amount"})]}),n.monthlyBreakdown.map(t=>{const o=I(t.month+"-01").toLocaleDateString("en-US",{month:"short",year:"numeric"}),c=a>0?t.collected/a*100:0;return e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-20 text-xs font-medium",children:o}),e.jsx("div",{className:"flex-1 h-1 bg-muted/15 rounded-sm overflow-hidden",children:e.jsx("div",{className:`h-full ${P.base} rounded-sm transition-all`,style:{width:`${c}%`}})}),e.jsx("div",{className:"w-20 text-right text-[13px] text-foreground/70",children:t.count}),e.jsx("div",{className:"w-32 text-right text-[14px] font-display font-medium",children:p(t.collected)})]},t.month)})]})]}),n.clientBreakdown&&n.clientBreakdown.length>0&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Income by Contact"}),e.jsx("div",{className:"mt-4 space-y-0 max-h-80 overflow-y-auto",children:n.clientBreakdown.map((t,o)=>e.jsxs("div",{className:`flex items-center justify-between py-3 border-b border-border/12 last:border-0 ${t.contactId?"cursor-pointer hover:bg-muted/30 transition-colors -mx-3 px-3 rounded":""}`,onClick:()=>{t.contactId&&(window.location.href=`/crm?tab=contacts&contactId=${t.contactId}`)},"data-testid":`income-client-${o}`,children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[14px] font-medium",children:t.name}),e.jsxs("p",{className:"text-[12px] text-foreground/65 mt-0.5",children:[t.count," payment",t.count!==1?"s":""]})]}),e.jsx("p",{className:"text-[14px] font-display font-medium",children:p(t.amount)})]},o))})]}),n.payments&&n.payments.length>0&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Payment History"}),e.jsx("div",{className:"mt-4 space-y-0 max-h-96 overflow-y-auto",children:n.payments.map(t=>e.jsxs("div",{className:`flex items-center justify-between py-3 border-b border-border/12 last:border-0 ${t.id?"cursor-pointer hover:bg-muted/30 transition-colors -mx-3 px-3 rounded":""}`,onClick:()=>{t.id&&(window.location.href=`/crm?tab=invoices&editInvoice=${t.id}`)},"data-testid":`payment-history-${t.id}`,children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[14px] font-medium",children:t.title}),e.jsxs("p",{className:"text-[12px] text-foreground/65 mt-0.5",children:[t.clientName," · ",K(t.date)]})]}),e.jsx("p",{className:"text-[14px] font-display font-medium",children:p(t.amount)})]},t.id))})]}),e.jsx(ie,{dates:s,reportType:"income"}),n.paymentCount===0&&e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-sm text-foreground
5/70 italic",children:"No income in this period"}),e.jsx("p",{className:"text-[12px] text-foreground/65 mt-1",children:"Send invoices and record payments to track income."})]})]})}function pt({dates:s}){const r=new URLSearchParams;s.from&&r.set("from",s.from),s.to&&r.set("to",s.to);const l=r.toString()?`?${r.toString()}`:"",{data:n,isLoading:i}=T({queryKey:["/api/crm/reports/expenses",s.from,s.to],queryFn:async()=>{const o=await w("GET",`/api/crm/reports/expenses${l}`);if(!o.ok)throw new Error("Failed");return o.json()}});if(i)return e.jsx(B,{className:"py-6"});if(!n)return null;const a=Math.max(...(n.monthlyBreakdown||[]).map(o=>o.amount),1),t=Math.max(...(n.categoryBreakdown||[]).map(o=>o.amount),1);return e.jsxs("div",{className:"space-y-8","data-testid":"report-expenses",children:[e.jsxs("div",{className:"flex items-stretch",children:[e.jsx(f,{label:"Total Expenses",value:p(n.totalExpenses)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Transactions",value:String(n.expenseCount)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Avg Expense",value:p(n.avgExpense)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Tax Deductible",value:p(n.taxDeductibleTotal)})]}),n.categoryBreakdown&&n.categoryBreakdown.length>0&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"By Category"}),e.jsx("div",{className:"mt-4 space-y-2",children:n.categoryBreakdown.map(o=>e.jsxs("div",{className:"flex items-center gap-3","data-testid":`exp-cat-${o.category}`,children:[e.jsx("div",{className:"w-36 text-xs truncate",children:o.category}),e.jsx("div",{className:"flex-1 h-1.5 bg-muted/15 rounded-sm overflow-hidden",children:e.jsx("div",{className:`h-full ${P.soft} rounded-sm`,style:{width:`${o.amount/t*100}%`}})}),e.jsxs("div",{className:"w-16 text-right text-[12px] text-foreground/70",children:[o.percentage,"%"]}),e.jsx("div",{className:"w-28 text-right text-[14px] font-display",children:p(o.amount)})]},o.category))})]}),n.monthlyBreakdown&&n.monthlyBreakdown.length>0&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Monthly Expenses"}),e.jsx("div",{className:"mt-4 space-y-3",children:n.monthlyBreakdown.map(o=>{const c=I(o.month+"-01").toLocaleDateString("en-US",{month:"short",year:"numeric"});return e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-20 text-xs font-medium",children:c}),e.jsx("div",{className:"flex-1 h-1 bg-muted/15 rounded-sm overflow-hidden",children:e.jsx("div",{className:`h-full ${P.base} rounded-sm transition-all`,style:{width:`${o.amount/a*100}%`}})}),e.jsx("div",{className:"w-32 text-right text-[14px] font-display font-medium",children:p(o.amount)})]},o.month)})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:[n.topVendors&&n.topVendors.length>0&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Top Vendors"}),e.jsx("div",{className:"mt-4 space-y-0 max-h-80 overflow-y-auto",children:n.topVendors.map((o,c)=>e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-border/12 last:border-0",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[14px] font-medium",children:o.vendor}),e.jsxs("p",{className:"text-[12px] text-foreground/65 mt-0.5",children:[o.count," transaction",o.count!==1?"s":""]})]}),e.jsx("p",{className:"text-[14px] font-display font-medium",children:p(o.amount)})]},c))})]}),n.recentExpenses&&n.recentExpenses.length>0&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Recent Expenses"}),e.jsx("div",{className:"mt-4 space-y-0 max-h-80 overflow-y-auto",children:n.recentExpenses.map(o=>e.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-border/12 last:border-0",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[14px] font-medium",children:o.payee}),e.jsxs("p",{className:"text-[12px] text-foreground/65 mt-0.5",children:[o.category," · ",K(o.date),o.taxDeductible&&e.jsx("span",{className:"ml-1.5 text-emerald-700 dark:text-emerald-400",children:"Tax Ded."})]})]}),e.jsx("p",{className:"text-[14px] font-display font-medium",children:p(o.amount)})]},o.id))})]})]}),n.expenseCount===0&&e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-sm text-foreground
5/70 italic",children:"No expenses in this period"}),e.jsx("p",{className:"text-[12px] text-foreground/65 mt-1",children:"Log expenses or import from CSV to track spending."})]})]})}function pe({bucket:s,items:r,maxVal:l,expanded:n,onToggle:i,allowDismiss:a}){const{toast:t}=H(),[o,c]=j.useState(null),u=De({mutationFn:async x=>{const m=r.find(v=>v.id===x);m&&await w("PATCH",`/api/crm/invoices/${x}`,{status:"paid",amountPaid:m.totalAmount})},onSuccess:()=>{c(null),t({title:"Invoice dismissed and marked as paid"}),Z.refetchQueries({queryKey:["/api/crm/reports/receivables"]}),Z.refetchQueries({queryKey:["/api/crm/invoices"]})},onError:()=>{t({title:"Failed to dismiss invoice",variant:"destructive"})}}),h=r.length>0;return e.jsxs("div",{"data-testid":`ar-bucket-${s.key}`,children:[e.jsxs("button",{onClick:()=>h&&i(),className:`w-full flex items-center gap-4 py-2 rounded-md transition-colors ${h?"cursor-pointer hover:bg-muted/15":"cursor-default"} ${n?"bg-muted/10":""}`,"data-testid":`ar-bucket-toggle-${s.key}`,children:[e.jsxs("div",{className:"w-28 text-xs font-medium text-left flex items-center gap-1.5",children:[h&&e.jsx(Re,{className:`w-3 h-3 text-foreground/65 transition-transform ${n?"":"-rotate-90"}`}),!h&&e.jsx("span",{className:"w-3"}),s.label]}),e.jsx("div",{className:"flex-1 h-2 bg-muted/15 rounded-sm overflow-hidden",children:e.jsx("div",{className:`h-full ${s.color} rounded-sm transition-all`,style:{width:`${(r.reduce((x,m)=>x+m.remaining,0)||0)/l*100}%`}})}),e.jsxs("div",{className:"w-16 text-right text-[12px] text-foreground/70",children:[r.length," inv"]}),e.jsx("div",{className:"w-32 text-right text-[14px] font-display font-medium",children:p(r.reduce((x,m)=>x+m.remaining,0))})]}),n&&r.length>0&&e.jsx("div",{className:"ml-[7.5rem] mt-1 mb-3 space-y-0 max-h-72 overflow-y-auto border-l-2 border-border/12 pl-4",children:r.map(x=>e.jsx("div",{className:"border-b border-border/8 last:border-0",children:o===x.id?e.jsxs("div",{className:"flex items-center justify-between py-3 px-2 -mx-1 bg-red-50/50 dark:bg-red-950/20 rounded",children:[e.jsx("p",{className:"text-[13px] text-foreground/80",children:"Dismiss this invoice and mark as paid?"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>c(null),className:"text-[12px] tracking-[0.1em] uppercase text-foreground/70 hover:text-foreground transition-colors px-2 py-1","data-testid":`button-dismiss-cancel-${x.id}`,children:"Cancel"}),e.jsx("button",{onClick:()=>u.mutate(x.id),disabled:u.isPending&&u.variables===x.id,className:"text-[12px] tracking-[0.1em] uppercase text-red-600 hover:text-red-700 font-medium transition-colors px-2 py-1","data-testid":`button-dismiss-confirm-${x.id}`,children:u.isPending?"Dismissing...":"Yes, Dismiss"})]})]}):e.jsxs("div",{className:"flex items-center justify-between py-2.5 text-left rounded px-2 -mx-1 group",children:[e.jsxs("button",{onClick:()=>{window.location.href=`/crm?tab=invoices&editInvoice=${x.id}`},className:"flex-1 text-left cursor-pointer hover:bg-muted/15 transition-colors rounded py-0.5","data-testid":`ar-invoice-${x.id}`,children:[e.jsx("p",{className:"text-[14px] font-medium",children:x.title}),e.jsxs("p",{className:"text-[12px] text-foreground/65 mt-0.5",children:[x.clientName,x.dueDate?` · Due ${K(x.dueDate)}`:" · No due date",x.daysOverdue>0&&e.jsxs("span",{className:"ml-1.5 text-red-700 dark:text-red-400",children:[x.daysOverdue,"d overdue"]}),x.daysUntilDue>0&&e.jsxs("span",{className:"ml-1.5 text-foreground/70",children:["in ",x.daysUntilDue,"d"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("p",{className:"text-[14px] font-display font-medium",children:p(x.remaining)}),a&&e.jsx("button",{onClick:m=>{m.stopPropagation(),c(x.id)},className:"transition-opacity p-1 rounded hover:bg-red-100/50 dark:hover:bg-red-900/20",title:"Dismiss (mark as paid)","data-testid":`button-dismiss-${x.id}`,children:e.jsx(Le,{className:"w-3.5 h-3.5 text-foreground/65 hover:text-red-500 transition-colors"})})]})]})},x.id))})]})}function ut(){const[s,r]=j.useState(null),{data:l,isLoading:n}=T({queryKey:["/api/crm/reports/receivables"],queryFn:async()=>{const c=await w("GET","/api/crm/reports/receivables");if(!c.ok)throw new Error("Failed");return c.json()}});if(n)return e.jsx(B,{className:"py-6"});if(!l)return null;const i=[{key:"pd30",label:"1-30 Days",color:"bg-red-500/35"},{key:"pd60",label:"31-60 Days",color:"bg-red-500/50"},{key:"pd90",label:"61-90 Days",color:"bg-red-500/70"},{key:"pdOver90",label:"90+ Days",color:"bg-red-600"}],a=[{key:"dueToday",label:"Due Today",color:"bg-primary/60"},{key:"next30",label:"1-30 Days",color:"bg-primary/50"},{key:"next60",label:"31-60 Days",color:"bg-primary/40"},{key:"next90",label:"61-90 Days",color:"bg-primary/30"},{key:"beyond90",label:"90+ Days",color:"bg-primary/20"},{key:"noDueDate",label:"No Due Date",color:P.neutral}],t=[...i,...a].map(c=>({...c,items:l.aged[c.key]||[]})),o=Math.max(...t.map(c=>c.items.reduce((u,h)=>u+h.remaining,0)),1);return e.jsxs("div",{className:"space-y-8","data-testid":"report-receivables",children:[e.jsxs("div",{className:"flex items-stretch",children:[e.jsx(f,{label:"Total Outstanding",value:p(l.totalOutstanding)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Past Due",value:p(l.totalPastDue||0)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Upcoming",value:p(l.totalUpcoming||0)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Open Invoices",value:String(l.invoiceCount)})]}),e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(y,{children:"Past Due"}),(l.pastDueCount||0)>0&&e.jsxs("span",{className:"text-[12px] tracking-[0.1em] uppercase text-red-700 dark:text-red-400 font-medium",children:[l.pastDueCount," invoice",l.pastDueCount!==1?"s":""]})]}),e.jsx("div",{className:"mt-4 space-y-1",children:i.map(c=>e.jsx(pe,{bucket:c,items:l.aged[c.key]||[],maxVal:o,expanded:s===c.key,onToggle:()=>r(s===c.key?null:c.key),allowDismiss:!0},c.key))}),(l.pastDueCount||0)===0&&e.jsx("p",{className:"text-[12px] text-foreground
5/70 italic mt-3",children:"No past due invoices"})]}),e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Upcoming"}),e.jsx("div",{className:"mt-4 space-y-1",children:a.map(c=>e.jsx(pe,{bucket:c,items:l.aged[c.key]||[],maxVal:o,expanded:s===c.key,onToggle:()=>r(s===c.key?null:c.key)},c.key))})]}),l.invoiceCount===0&&e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-sm text-foreground/70 italic",children:"All caught up on invoices"}),e.jsx("p",{className:"text-[12px] text-foreground/65 mt-1",children:"Outstanding balances will show here once you send invoices to clients."})]})]})}function ht({dates:s}){const r=new URLSearchParams;s.from&&r.set("from",s.from),s.to&&r.set("to",s.to);const l=r.toString()?`?${r.toString()}`:"",{data:n,isLoading:i}=T({queryKey:["/api/crm/reports/lead-sources",s.from,s.to],queryFn:async()=>{const m=await w("GET",`/api/crm/reports/lead-sources${l}`);if(!m.ok)throw new Error("Failed");return m.json()}});if(i)return e.jsx(B,{className:"py-6"});if(!n)return null;const{totalLeads:a,totalBooked:t,sources:o,monthly:c}=n,u=o.length>0?o[0].source:"N/A",h=a>0?Math.round(t/a*1e4)/100:0,x=Math.max(...o.map(m=>m.count),1);return e.jsxs("div",{className:"space-y-8","data-testid":"report-lead-sources",children:[e.jsxs("div",{className:"flex items-stretch",children:[e.jsx(f,{label:"Total Leads",value:String(a)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Booked",value:String(t)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Conversion",value:`${h}%`}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Top Source",value:u})]}),o.length>0&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Where Your Leads Come From"}),e.jsx("div",{className:"mt-5 space-y-3",children:o.map((m,v)=>{const b=a>0?Math.round(m.count/a*100):0;return e.jsxs("div",{className:"flex items-center gap-4","data-testid":`lead-source-${v}`,children:[e.jsx("div",{className:"w-44 text-xs font-medium truncate",children:m.source}),e.jsx("div",{className:"flex-1 h-2.5 bg-muted/15 rounded-sm overflow-hidden",children:e.jsx("div",{className:`h-full ${it(v)} rounded-sm transition-all`,style:{width:`${m.count/x*100}%`}})}),e.jsx("div",{className:"w-12 text-right text-[13px] text-foreground/70",children:m.count}),e.jsxs("div",{className:"w-12 text-right text-[12px] text-foreground/65",children:[b,"%"]}),e.jsxs("div",{className:"w-20 text-right text-[12px] text-foreground/65",children:[m.booked," booked"]}),e.jsxs("div",{className:"w-16 text-right text-[12px] text-foreground/65",children:[m.conversionRate,"%"]})]},m.source)})}),e.jsxs("div",{className:"mt-3 flex items-center gap-4 text-[12px] tracking-[0.12em] uppercase text-foreground/70 border-t border-border/8 pt-2",children:[e.jsx("div",{className:"w-44",children:"Source"}),e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:"w-12 text-right",children:"Leads"}),e.jsx("div",{className:"w-12 text-right",children:"Share"}),e.jsx("div",{className:"w-20 text-right",children:"Booked"}),e.jsx("div",{className:"w-16 text-right",children:"Conv. %"})]})]}),o.length>0&&o.some(m=>m.revenue>0)&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Revenue by Source"}),e.jsx("div",{className:"mt-5 space-y-2.5",children:o.filter(m=>m.revenue>0).sort((m,v)=>v.revenue-m.revenue).map((m,v)=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-44 text-xs font-medium truncate",children:m.source}),e.jsx("div",{className:"flex-1 h-1.5 bg-muted/15 rounded-sm overflow-hidden",children:e.jsx("div",{className:`h-full ${P.base} rounded-sm`,style:{width:`${m.revenue/Math.max(...o.map(b=>b.revenue),1)*100}%`}})}),e.jsx("div",{className:"w-32 text-right text-[14px] font-display font-medium",children:p(m.revenue)})]},m.source))})]}),c&&c.length>1&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Monthly Trend"}),e.jsx("div",{className:"mt-5 overflow-x-auto",children:e.jsxs("table",{className:"w-full text-[13px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[12px] tracking-[0.12em] uppercase text-foreground
5/70",children:[e.jsx("th",{className:"text-left pb-2 font-medium w-24",children:"Month"}),o.slice(0,6).map(m=>e.jsx("th",{className:"text-right pb-2 font-medium w-20 truncate max-w-[80px]",children:m.source},m.source)),e.jsx("th",{className:"text-right pb-2 font-medium",children:"Total"})]})}),e.jsx("tbody",{children:c.map(m=>{const v=Object.values(m.sources).reduce((d,E)=>d+E,0),[b,F]=m.month.split("-"),L=new Date(Number(b),Number(F)-1).toLocaleDateString("en-US",{month:"short",year:"numeric"});return e.jsxs("tr",{className:"border-t border-border/6",children:[e.jsx("td",{className:"py-1.5 text-foreground/70",children:L}),o.slice(0,6).map(d=>e.jsx("td",{className:"text-right py-1.5 text-foreground/70",children:m.sources[d.source]||0},d.source)),e.jsx("td",{className:"text-right py-1.5 font-medium",children:v})]},m.month)})})]})})]}),e.jsx(ie,{dates:s,reportType:"lead-sources"}),a===0&&e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-sm text-foreground/70 italic",children:"No lead data for this period"}),e.jsx("p",{className:"text-[12px] text-foreground/65 mt-1",children:'Add a "How did you hear about us?" field to your lead forms to start tracking sources.'})]})]})}function gt(){const{data:s,isLoading:r}=T({queryKey:["/api/crm/reports/sales-pipeline"],queryFn:async()=>{const a=await w("GET","/api/crm/reports/sales-pipeline");if(!a.ok)throw new Error("Failed");return a.json()}});if(r)return e.jsx(B,{className:"py-6"});if(!s)return null;const l={lead:"Lead",proposal_sent:"Proposal Sent",booked:"Booked",completed:"Completed",lost:"Lost"},n={lead:"bg-primary/20",proposal_sent:"bg-primary/30",booked:"bg-primary/45",completed:"bg-primary/60",lost:P.neutral},i=Math.max(...Object.values(s.stages).map(a=>a.value),1);return e.jsxs("div",{className:"space-y-8","data-testid":"report-pipeline",children:[e.jsxs("div",{className:"flex items-stretch",children:[e.jsx(f,{label:"Total Contacts",value:String(s.totalContacts)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Pipeline Value",value:p(s.totalPipelineValue)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Booked Value",value:p(s.bookedValue)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Conversion Rate",value:`${s.conversionRate}%`})]}),e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Pipeline Stages"}),e.jsx("div",{className:"mt-4 space-y-3",children:["lead","proposal_sent","booked","completed","archive"].map(a=>{const t=s.stages[a]||{count:0,value:0};return e.jsxs("div",{className:"flex items-center gap-4","data-testid":`pipe-stage-${a}`,children:[e.jsx("div",{className:"w-32 text-xs font-medium",children:l[a]||a}),e.jsx("div",{className:"flex-1 h-2 bg-muted/15 rounded-sm overflow-hidden",children:e.jsx("div",{className:`h-full ${n[a]||P.neutral} rounded-sm transition-all`,style:{width:`${t.value/i*100}%`}})}),e.jsx("div",{className:"w-16 text-right text-[13px] text-foreground/70",children:t.count}),e.jsx("div",{className:"w-32 text-right text-[14px] font-display font-medium",children:p(t.value)})]},a)})})]}),s.sourceBreakdown&&s.sourceBreakdown.length>0&&e.jsxs("div",{className:"pt-8 border-t border-border/12",children:[e.jsx(y,{children:"Lead Sources"}),e.jsx("div",{className:"mt-4 space-y-2",children:s.sourceBreakdown.map(a=>{const t=s.totalContacts>0?Math.round(a.count/s.totalContacts*100):0;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-32 text-xs truncate",children:a.source}),e.jsx("div",{className:"flex-1 h-1 bg-muted/15 rounded-sm overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary/15 rounded-sm",style:{width:`${t}%`}})}),e.jsx("div",{className:"w-12 text-right text-[13px] text-foreground/70",children:a.count}),e.jsxs("div",{className:"w-12 text-right text-[12px] text-foreground/65",children:[t,"%"]})]},a.source)})})]}),s.totalContacts===0&&e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-sm text-foreground/70 italic",children:"No contacts in pipeline"}
5),e.jsx("p",{className:"text-[12px] text-foreground/65 mt-1",children:"Add contacts to start tracking your pipeline."})]})]})}function us(){const[s,r]=j.useState("all"),[l,n]=j.useState(""),[i,a]=j.useState(null),t=Pe(l,300),o=new URLSearchParams;s!=="all"&&o.set("status",s),t&&o.set("contactEmail",t);const c=o.toString()?`?${o.toString()}`:"",{data:u,isLoading:h}=T({queryKey:["/api/crm/email-log",s,t],queryFn:async()=>{const d=await w("GET",`/api/crm/email-log${c}`);if(!d.ok)throw new Error("Failed");return d.json()}}),{data:x}=T({queryKey:["/api/crm/email-log",i],queryFn:async()=>{if(!i)return null;const d=await w("GET",`/api/crm/email-log/${i}`);if(!d.ok)throw new Error("Failed");return d.json()},enabled:!!i}),m=u?.emails||[],v=u?.stats||{total:0,delivered:0,opened:0},b=v.total>0?Math.round(v.opened/v.total*100):0,F={sent:"bg-blue-50/60 text-blue-700 dark:bg-blue-900/20 dark:text-blue-300",delivered:"bg-green-50/60 text-green-700 dark:bg-green-900/20 dark:text-green-300",opened:"bg-violet-50/60 text-violet-700 dark:bg-violet-900/20 dark:text-violet-300",bounced:"bg-red-50/60 text-red-700 dark:bg-red-900/20 dark:text-red-300",spam:"bg-red-50/60 text-red-700 dark:bg-red-900/20 dark:text-red-300",failed:"bg-amber-50/60 text-amber-700 dark:bg-amber-900/20 dark:text-amber-300"};function L(d){return d?new Date(d).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"â"}return e.jsxs("div",{className:"space-y-8","data-testid":"email-log-view",children:[e.jsx("div",{className:"flex items-end justify-between flex-wrap gap-3",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-[12px] tracking-[0.35em] uppercase text-foreground/70 font-medium mb-3",children:"Communications"}),e.jsx("h2",{className:"text-xl font-display font-light tracking-tight",children:"Email Log"}),e.jsx("p",{className:"text-[12px] text-foreground/65 mt-2",children:"Every email Colara sends on your behalf, with delivery and open tracking"})]})}),e.jsx("div",{className:"flex items-stretch","data-testid":"email-stats-row",children:[{label:"Total Sent",value:String(v.total)},{label:"Delivered",value:String(v.delivered)},{label:"Opened",value:String(v.opened)},{label:"Open Rate",value:`${b}%`}].map((d,E,D)=>e.jsxs("div",{className:"relative flex-1 text-center py-7",children:[e.jsx("p",{className:"text-2xl sm:text-3xl font-extralight tracking-tight font-display","data-testid":`text-email-${d.label.toLowerCase().replace(/\s/g,"-")}`,children:d.value}),e.jsx("p",{className:"text-[12px] tracking-[0.25em] uppercase text-foreground/65 mt-3 font-medium",children:d.label}),E<D.length-1&&e.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 h-10 w-px bg-border/8"})]},d.label))}),e.jsxs("div",{className:"pt-6 border-t border-border/12",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("p",{className:"text-[12px] tracking-[0.25em] uppercase text-foreground/75",children:"All Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_e,{className:"w-3.5 h-3.5 absolute left-2.5 top-1/2 -translate-y-1/2 text-foreground/70"}),e.jsx(q,{value:l,onChange:d=>n(d.target.value),placeholder:"Filter by email...",className:"h-8 w-48 pl-8 bg-muted/40 border-0 text-[13px]","data-testid":"input-email-log-search"})]}),e.jsxs(O,{value:s,onValueChange:r,children:[e.jsx(V,{className:"w-36 h-8 bg-muted/40 border-0 text-[13px]","data-testid":"select-email-status-filter",children:e.jsx(G,{placeholder:"All Statuses"})}),e.jsxs(Y,{children:[e.jsx(R,{value:"all",children:"All Statuses"}),e.jsx(R,{value:"sent",children:"Sent"}),e.jsx(R,{value:"delivered",children:"Delivered"}),e.jsx(R,{value:"opened",children:"Opened"}),e.jsx(R,{value:"bounced",children:"Bounced"})]})]})]})]}),h?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(ye,{className:"w-6 h-6 animate-spin text-primary"})}):m.length===0?e.jsxs("div",{className:"text-center py-16",children:[e.jsx(be,{className:"w-10 h-10 mx-auto mb-3 text-muted-foreground/40"}
5),e.jsx("p",{className:"text-[14px] text-foreground/65",children:"Your email history lives here"}),e.jsx("p",{className:"text-[12px] text-foreground/70 mt-1",children:"Every email you send to clients shows up with open tracking â see who opened what and when."})]}):e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 text-[12px] tracking-[0.2em] uppercase text-foreground/65",children:[e.jsx("div",{className:"w-24 shrink-0",children:"Sent"}),e.jsx("div",{className:"flex-1",children:"Subject"}),e.jsx("div",{className:"w-40 shrink-0",children:"Recipient"}),e.jsx("div",{className:"w-28 shrink-0 text-center",children:"Type"}),e.jsx("div",{className:"w-20 shrink-0 text-center",children:"Status"}),e.jsx("div",{className:"w-32 shrink-0 text-right",children:"Tracking"})]}),m.map(d=>{const E=le(d.emailType),D=F[d.status]||F.sent;return e.jsxs("button",{onClick:()=>a(d.id),className:"w-full flex items-center gap-2 px-3 py-2.5 rounded-md hover:bg-muted/40 transition-colors group text-left","data-testid":`email-log-row-${d.id}`,children:[e.jsx("div",{className:"w-24 shrink-0 text-[12px] text-foreground/70",children:L(d.createdAt)}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"text-[14px] font-light truncate",children:d.subject})}),e.jsx("div",{className:"w-40 shrink-0 text-[12px] text-foreground/70 truncate",children:d.recipient}),e.jsx("div",{className:"w-28 shrink-0 text-center overflow-hidden",children:e.jsx("span",{className:"text-[12px] tracking-wider uppercase text-foreground/65 block truncate",children:E})}),e.jsx("div",{className:"w-20 shrink-0 text-center",children:e.jsx("span",{className:`text-[12px] tracking-wider uppercase px-1.5 py-0.5 rounded whitespace-nowrap ${D}`,children:d.status})}),e.jsx("div",{className:"w-32 shrink-0 text-right",children:d.openedAt?e.jsxs("div",{className:"flex flex-col items-end gap-0.5",children:[e.jsx("span",{className:"text-[12px] text-emerald-600 font-medium tracking-wider uppercase",children:"Opened"}),e.jsx("span",{className:"text-[12px] text-foreground/70",children:L(d.openedAt)})]}):d.status==="bounced"||d.bouncedAt?e.jsx("span",{className:"text-[12px] text-red-500 font-medium tracking-wider uppercase",children:"Bounced"}):d.status==="failed"?e.jsx("span",{className:"text-[12px] text-red-500 font-medium tracking-wider uppercase",children:"Failed"}):d.status==="spam"?e.jsx("span",{className:"text-[12px] text-orange-500 font-medium tracking-wider uppercase",children:"Spam"}):d.deliveredAt||d.status==="delivered"?e.jsx("span",{className:"text-[12px] text-blue-700 dark:text-blue-400 font-medium tracking-wider uppercase",children:"Delivered"}):e.jsx("span",{className:"text-[12px] text-foreground/65 tracking-wider uppercase",children:"Sent"})})]},d.id)})]})]}),i&&x&&e.jsx(he,{open:!0,onOpenChange:()=>a(null),children:e.jsxs(ge,{className:"max-w-2xl max-h-[85vh] overflow-y-auto","data-testid":"dialog-email-detail",children:[e.jsx(fe,{children:e.jsx(je,{className:"text-lg font-display font-light",children:x.subject})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-[13px]",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[12px] tracking-[0.2em] uppercase text-foreground/65 mb-1",children:"To"}),e.jsx("p",{children:x.recipient})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[12px] tracking-[0.2em] uppercase text-foreground/65 mb-1",children:"Sent"}),e.jsx("p",{children:L(x.createdAt)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[12px] tracking-[0.2em] uppercase text-foreground/65 mb-1",children:"Status"}),e.jsx("span",{className:`text-[12px] tracking-wider uppercase px-2 py-0.5 rounded ${F[x.status]||F.sent}`,children:x.status})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[12px] tracking-[0.2em] uppercase text-foreground/65 mb-1",children:"Type"}),e.jsx("p",{className:"text-foreground/65",children:le(x.emailType)})]})]}),e.jsxs("div",{className:"border-t border-border/12 pt-4",children:[e.jsx("p",{className:"text-[12px] tracking-[0.2em] uppercase text-foreground
5/65 mb-3",children:"Delivery Timeline"}),e.jsxs("div",{className:"space-y-2",children:[[{label:"Sent",time:x.createdAt,icon:Oe},{label:"Delivered",time:x.deliveredAt,icon:Ve},{label:"Opened",time:x.openedAt,icon:Se},...x.clickedAt?[{label:"Link Clicked",time:x.clickedAt,icon:$e}]:[],...x.bouncedAt?[{label:"Bounced",time:x.bouncedAt,icon:J}]:[]].map(d=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(d.icon,{className:`w-3.5 h-3.5 ${d.time?"text-green-700 dark:text-green-400":"text-muted-foreground"}`}),e.jsx("span",{className:`text-[13px] ${d.time?"text-foreground":"text-foreground/70"}`,children:d.label}),d.time&&e.jsx("span",{className:"text-[12px] text-foreground/65 ml-auto",children:L(d.time)})]},d.label)),x.bounceReason&&e.jsx("p",{className:"text-[12px] text-red-700 dark:text-red-400 ml-6 mt-1",children:x.bounceReason})]})]}),x.htmlContent&&e.jsxs("div",{className:"border-t border-border/12 pt-4",children:[e.jsx("p",{className:"text-[12px] tracking-[0.2em] uppercase text-foreground/65 mb-3",children:"Email Content"}),e.jsx("div",{className:"bg-muted/10 rounded-lg p-4 max-h-[300px] overflow-y-auto text-[14px]",dangerouslySetInnerHTML:{__html:Fe.sanitize(x.htmlContent)},"data-testid":"email-content-preview"})]})]})]})})]})}function ft({data:s}){if(!s||s.length===0)return null;const r=Math.max(...s.map(i=>i.revenue),1),l=Math.max(Math.floor(100/s.length)-2,4),n=180;return e.jsxs("div",{"data-testid":"chart-revenue-trend",children:[e.jsx(y,{children:"Monthly Revenue Trend"}),e.jsxs("div",{className:"mt-4 flex items-end gap-1 h-[180px] relative",children:[[.25,.5,.75,1].map(i=>e.jsx("div",{className:"absolute left-0 right-0 border-t border-border/8",style:{bottom:`${i*n}px`},children:e.jsx("span",{className:"text-[11px] text-foreground/65 absolute -top-3 -left-1",children:p(r*i)})},i)),s.map((i,a)=>{const t=r>0?i.revenue/r*n:0,o=I(i.month+"-01").toLocaleDateString("en-US",{month:"short"});return e.jsxs("div",{className:"flex flex-col items-center flex-1 min-w-0 relative group","data-testid":`bar-revenue-${i.month}`,children:[e.jsx("div",{className:"absolute -top-6 bg-foreground text-background text-[12px] px-1.5 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-10 pointer-events-none",children:p(i.revenue)}),e.jsx("div",{className:"w-full flex justify-center",style:{height:`${n}px`,alignItems:"flex-end"},children:e.jsx("div",{className:"rounded-t-sm transition-all duration-300 hover:opacity-80",style:{width:`${l}%`,minWidth:"8px",maxWidth:"36px",height:`${Math.max(t,2)}px`,background:i.revenue>0?"linear-gradient(to top, hsl(var(--primary) / 0.25), hsl(var(--primary) / 0.5))":"hsl(var(--muted) / 0.4)"}})}),e.jsx("span",{className:"text-[11px] text-foreground/70 mt-1.5 truncate w-full text-center",children:o})]},i.month)})]})]})}function jt({pipelineData:s}){if(!s)return null;const r=["lead","proposal_sent","booked","completed"],l={lead:"Lead",proposal_sent:"Proposal Sent",booked:"Booked",completed:"Completed"},n=["bg-primary/20","bg-primary/30","bg-primary/45","bg-primary/60"],i=r.map(t=>s.stages?.[t]?.count||0),a=Math.max(i[0],1);return e.jsxs("div",{"data-testid":"chart-conversion-funnel",children:[e.jsx(y,{children:"Conversion Funnel"}),e.jsx("div",{className:"mt-5 space-y-2",children:r.map((t,o)=>{const c=i[o],u=c/a*100,h=o>0&&i[o-1]>0?Math.round((1-c/i[o-1])*100):0,x=i[0]>0?Math.round(c/i[0]*100):0;return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`funnel-stage-${t}`,children:[e.jsx("div",{className:"w-28 text-xs font-medium",children:l[t]}),e.jsx("div",{className:"flex-1 flex items-center",children:e.jsx("div",{className:"relative w-full",children:e.jsx("div",{className:"h-8 bg-muted/10 rounded-sm overflow-hidden",style:{width:"100%"},children:e.jsx("div",{className:`h-full ${n[o]} rounded-sm transition-all duration-500 flex items-center`,style:{width:`${Math.max(u,3)}%`},children:e.jsx("span",{className:"text-[12px] font-medium ml-2 whitespace-nowrap",children:c})})})})}),e.jsxs("div",{className:"w-16 text-right text-[12px] text-foreground
5/65",children:[x,"%"]}),o>0&&h>0&&e.jsxs("div",{className:"w-20 text-right text-[12px] text-red-700 dark:text-red-400",children:["-",h,"% drop"]}),o===0&&e.jsx("div",{className:"w-20"})]},t)})}),i[0]===0&&e.jsx("p",{className:"text-[12px] text-foreground/65 mt-4 italic",children:"Add your first lead to see your conversion funnel â track every inquiry from first contact to booked."})]})}function yt({data:s}){if(!s)return null;function r(n){return n<1?`${Math.round(n*60)}m`:n<24?`${Math.round(n*10)/10}h`:`${Math.round(n/24*10)/10}d`}const l=s.monthly&&s.monthly.length>=2?s.monthly[s.monthly.length-1].avgHours<s.monthly[s.monthly.length-2].avgHours:null;return e.jsxs("div",{"data-testid":"card-response-time",children:[e.jsx(y,{children:"Response Time Analytics"}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex items-stretch",children:[e.jsx(f,{label:"Avg Response",value:r(s.avgHours),sub:`${s.totalMeasured} leads measured`}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Median",value:r(s.medianHours)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Under 1 Hour",value:`${s.under1hPercent}%`}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Under 24 Hours",value:`${s.under24hPercent}%`})]}),l!==null&&e.jsx("div",{className:"flex items-center justify-center gap-2 mt-3 text-[12px]",children:l?e.jsxs(e.Fragment,{children:[e.jsx(ee,{className:"w-3.5 h-3.5 text-emerald-700 dark:text-emerald-400"}),e.jsx("span",{className:"text-emerald-700 dark:text-emerald-400",children:"Response time improving"})]}):e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"w-3.5 h-3.5 text-amber-700 dark:text-amber-400"}),e.jsx("span",{className:"text-amber-700 dark:text-amber-400",children:"Response time increasing"})]})}),s.monthly&&s.monthly.length>0&&e.jsxs("div",{className:"mt-6 pt-6 border-t border-border/12",children:[e.jsx(y,{children:"Monthly Trend"}),e.jsx("div",{className:"mt-3 space-y-2",children:s.monthly.map(n=>{const i=I(n.month+"-01").toLocaleDateString("en-US",{month:"short",year:"numeric"}),a=Math.max(...s.monthly.map(o=>o.avgHours),1),t=n.avgHours/a*100;return e.jsxs("div",{className:"flex items-center gap-3","data-testid":`response-month-${n.month}`,children:[e.jsx("div",{className:"w-20 text-xs font-medium",children:i}),e.jsx("div",{className:"flex-1 h-1.5 bg-muted/15 rounded-sm overflow-hidden",children:e.jsx("div",{className:`h-full ${P.base} rounded-sm transition-all`,style:{width:`${t}%`}})}),e.jsx("div",{className:"w-12 text-right text-[12px] text-foreground/70",children:r(n.avgHours)}),e.jsxs("div",{className:"w-16 text-right text-[12px] text-foreground/70",children:[n.count," leads"]})]},n.month)})})]}),s.totalMeasured===0&&e.jsxs("div",{className:"text-center py-10",children:[e.jsx("p",{className:"text-sm text-foreground/70 italic",children:"Response time tracking starts with your first activity"}),e.jsx("p",{className:"text-[12px] text-foreground/65 mt-1",children:"Log calls, emails, and follow-ups on your leads â we'll calculate your average response time automatically."})]})]})]})}function bt({data:s}){if(!s)return null;const r={high:"bg-emerald-500/15 text-emerald-700 dark:text-emerald-400",medium:"bg-amber-400/15 text-amber-700 dark:text-amber-400",low:"bg-red-400/15 text-red-700 dark:text-red-400"},l={high:"High",medium:"Medium",low:"Low"},n=[...s.historical||[],...(s.forecast||[]).map(t=>({month:t.month,revenue:t.projected}))],i=Math.max(...n.map(t=>t.revenue),1),a=160;return e.jsxs("div",{"data-testid":"section-revenue-forecast",children:[e.jsx(y,{children:"Revenue Forecast"}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex items-stretch",children:[e.jsx(f,{label:"Avg Monthly",value:p(s.avgMonthly)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Recent Avg",value:p(s.recentAvg),sub:"Last 6 months"}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Booked Unpaid",value:p(s.bookedUnpaid)}),e.jsx("div",{className:"w-px bg-border/8 my-4"}),e.jsx(f,{label:"Pipeline",value:p(s.pipelineValue)})]}),e.jsxs("div",{className:"mt-6 pt-6 border-t border-border/12",children:[e.jsx(y,{children:"12-Month History + 3-
5Month Projection"}),e.jsxs("div",{className:"mt-4 flex items-end gap-0.5 h-[160px]",children:[s.historical?.map(t=>{const o=i>0?t.revenue/i*a:0,c=I(t.month+"-01").toLocaleDateString("en-US",{month:"narrow"});return e.jsxs("div",{className:"flex flex-col items-center flex-1 min-w-0 group relative","data-testid":`forecast-bar-${t.month}`,children:[e.jsx("div",{className:"absolute -top-6 bg-foreground text-background text-[11px] px-1 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-10 pointer-events-none",children:p(t.revenue)}),e.jsx("div",{className:"w-full flex justify-center",style:{height:`${a}px`,alignItems:"flex-end"},children:e.jsx("div",{className:"rounded-t-sm transition-all",style:{width:"70%",minWidth:"6px",maxWidth:"28px",height:`${Math.max(o,1)}px`,background:"hsl(var(--primary) / 0.4)"}})}),e.jsx("span",{className:"text-[11px] text-foreground/65 mt-1",children:c})]},t.month)}),s.forecast?.map(t=>{const o=i>0?t.projected/i*a:0,c=I(t.month+"-01").toLocaleDateString("en-US",{month:"narrow"});return e.jsxs("div",{className:"flex flex-col items-center flex-1 min-w-0 group relative","data-testid":`forecast-projected-${t.month}`,children:[e.jsxs("div",{className:"absolute -top-6 bg-foreground text-background text-[11px] px-1 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-10 pointer-events-none",children:[p(t.projected)," (projected)"]}),e.jsx("div",{className:"w-full flex justify-center",style:{height:`${a}px`,alignItems:"flex-end"},children:e.jsx("div",{className:"rounded-t-sm transition-all",style:{width:"70%",minWidth:"6px",maxWidth:"28px",height:`${Math.max(o,1)}px`,background:"repeating-linear-gradient(135deg, hsl(var(--primary) / 0.18), hsl(var(--primary) / 0.18) 2px, hsl(var(--primary) / 0.06) 2px, hsl(var(--primary) / 0.06) 4px)",border:"1px dashed hsl(var(--primary) / 0.35)"}})}),e.jsx("span",{className:"text-[11px] text-foreground/65 mt-1",children:c})]},t.month)})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 justify-center text-[12px] text-foreground/70",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`w-3 h-2 rounded-sm ${P.base}`})," Actual"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 h-2 rounded-sm border border-dashed border-primary/40 bg-primary/10"})," Projected"]})]})]}),s.forecast&&s.forecast.length>0&&e.jsxs("div",{className:"mt-6 pt-6 border-t border-border/12",children:[e.jsx(y,{children:"Projected Revenue"}),e.jsx("div",{className:"mt-3 space-y-2",children:s.forecast.map(t=>{const o=I(t.month+"-01").toLocaleDateString("en-US",{month:"long",year:"numeric"});return e.jsxs("div",{className:"flex items-center justify-between py-2 border-b border-border/8 last:border-0","data-testid":`forecast-row-${t.month}`,children:[e.jsx("div",{children:e.jsx("p",{className:"text-[14px] font-medium",children:o})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:`text-[11px] tracking-[0.1em] uppercase px-2 py-0.5 rounded-full ${r[t.confidence]}`,children:[l[t.confidence]," confidence"]}),e.jsx("p",{className:"text-[14px] font-display font-medium",children:p(t.projected)})]})]},t.month)})})]}),s.dataPoints===0&&e.jsxs("div",{className:"text-center py-10",children:[e.jsx("p",{className:"text-sm text-foreground/70 italic",children:"Not enough data to forecast"}),e.jsx("p",{className:"text-[12px] text-foreground/65 mt-1",children:"Record payments through invoices to build revenue history for forecasting."})]}),s.trendDirection&&s.dataPoints>=2&&e.jsx("div",{className:"flex items-center justify-center gap-2 mt-4 text-[12px]",children:s.trendDirection==="up"?e.jsxs(e.Fragment,{children:[e.jsx(we,{className:"w-3.5 h-3.5 text-emerald-700 dark:text-emerald-400"}),e.jsx("span",{className:"text-emerald-700 dark:text-emerald-400",children:"Revenue trending upward"})]}):e.jsxs(e.Fragment,{children:[e.jsx(ee,{className:"w-3.5 h-3.5 text-amber-700 dark:text-amber-400"}),e.jsx("span",{className:"text-amber-700 dark:text-amber-400",children:"Revenue trending downward"})]})})]})]})}function vt(){const{data:s,isLoading:r}=T({queryKey:["/api/crm/reports/revenue-forecast"],queryFn:async()=>{const o=await w("GET","/api/crm/reports/revenue-forecast");if(!o.ok)throw new Error("Failed");return o.json()}}),{data:l,isLoading:n}=T({queryKey:["/api/crm/reports/response-time"],queryFn:async()=>{const o=await w("GET","/api/crm/reports/response-time");if(!o.ok)throw new Error("Failed");return o.json()}}),{data:i,isLoading:a}=T({queryKey:["/api/crm/reports/sales-pipeline"],queryFn:async()=>{const o=await w("GET","/api/crm/reports/sales-pipeline");if(!o.ok)throw new Error("Failed");return o.json()}});return r||n||a?e.jsx(B,{className:"py-6"}):e.jsxs("div",{className:"space-y-10","data-testid":"report-analytics",children:[s?.historical&&e.jsx(ft,{data:s.historical}),e.jsx("div",{className:"pt-8 border-t border-border/12",children:e.jsx(jt,{pipelineData:i})}),e.jsx("div",{className:"pt-8 border-t border-border/12",children:e.jsx(st,{})}),e.jsx("div",{className:"pt-8 border-t border-border/12",children:e.jsx(yt,{data:l})}),e.jsx("div",{className:"pt-8 border-t border-border/12",children:e.jsx(dt,{})}),e.jsx("div",{className:"pt-8 border-t border-border/12",children:e.jsx(bt,{data:s})}),e.jsx(Nt,{})]})}function Nt(){const{toast:s}=H(),{data:r}=T({queryKey:["/api/crm/settings"]}),[l,n]=j.useState(!1),i=async()=>{n(!0);try{const a=!r?.monthlyDigestEnabled;await w("PATCH","/api/crm/settings",{monthlyDigestEnabled:a}),Z.invalidateQueries({queryKey:["/api/crm/settings"]}),s({title:a?"Monthly digest enabled":"Monthly digest disabled"})}catch{s({title:"Failed to update",variant:"destructive"})}finally{n(!1)}};return e.jsxs("div",{className:"pt-8 border-t border-border/12","data-testid":"panel-monthly-digest",children:[e.jsx(y,{children:"Monthly Business Snapshot"}
5),e.jsx("p",{className:"text-[12px] text-foreground/70 mt-1 mb-4",children:"Receive a monthly email on the 1st with key metrics: revenue, leads, bookings, outstanding invoices, and top lead source."}),e.jsxs("button",{onClick:i,disabled:l,className:`flex items-center gap-2 px-4 py-2 text-[12px] tracking-[0.1em] uppercase font-medium rounded border transition-colors ${r?.monthlyDigestEnabled?"bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-800":"text-foreground/70 border-border/15 hover:text-foreground hover:border-border/30"}`,"data-testid":"button-toggle-monthly-digest",children:[e.jsx(be,{className:"w-3.5 h-3.5"}),l?"Updating...":r?.monthlyDigestEnabled?"Enabled â Sends on the 1st":"Enable Monthly Digest"]})]})}function wt(){const{toast:s}=H(),r=new Date().getFullYear(),[l,n]=j.useState(`${r}-01-01`),[i,a]=j.useState(`${r}-12-31`),[t,o]=j.useState(!1),[c,u]=j.useState(String(r)),[h,x]=j.useState(!1),[m,v]=j.useState("tagged"),b=[];for(let d=r;d>=r-6;d--)b.push(String(d));const F=async()=>{o(!0);try{const d=new URLSearchParams;l&&d.set("from",l),i&&d.set("to",i);const E=await w("GET",`/api/crm/reports/transactions?${d.toString()}`);if(!E.ok)throw new Error("Failed");const D=await E.json(),N=["Date","Client","Invoice","Amount","Gratuity","Tax","Method","Source"],S=(D.transactions||[]).map(g=>[g.date?U(g.date):"",g.client,g.invoiceTitle,(g.amount/100).toFixed(2),(g.gratuity/100).toFixed(2),(g.tax/100).toFixed(2),g.method,g.source]);S.push(["","","","","","","",""]),S.push(["","","Gross payments",(D.grossPayments/100).toFixed(2),"","","",""]),S.push(["","","Refunds",(D.refunds/100).toFixed(2),"","","",""]),S.push(["","","Net collected",(D.netCollected/100).toFixed(2),"","","",""]),S.push(["","","Gratuity (incl.)","",(D.totalGratuity/100).toFixed(2),"","",""]),S.push(["","","Sales tax (incl.)","","",(D.totalTax/100).toFixed(2),"",""]),A(`transactions_${l}_to_${i}.csv`,N,S),s({title:"Transactions exported as CSV"})}catch{s({title:"Export failed",variant:"destructive"})}finally{o(!1)}},L=async()=>{x(!0);try{const d=await w("GET",`/api/crm/reports/contractor-1099?year=${encodeURIComponent(c)}&scope=${m}`);if(!d.ok)throw new Error("Failed");const E=await d.json();if(m==="tagged"&&(E.taggedCount??0)===0){s({title:"No contractor payments tagged yet",description:"Mark expenses with the âContractor payment (1099)â toggle, or switch to âAll expensesâ to export everything by payee."});return}const D=["Payee","Category","Total Paid","Payments","Over $600 (1099 hint)"],N=(E.vendors||[]).map(S=>[S.payee,S.category,(S.total/100).toFixed(2),String(S.count),S.over1099Threshold?"Yes":"No"]);N.push(["","","","",""]),N.push(["TOTAL","",(E.totalPaid/100).toFixed(2),"",""]),N.push(["","","","",""]),N.push(["Note",E.dataGap||"","","",""]),A(`contractor_1099_${E.year}.csv`,D,N),s({title:"Contractor summary exported as CSV"})}catch{s({title:"Export failed",variant:"destructive"})}finally{x(!1)}};return e.jsxs("div",{className:"space-y-6","data-testid":"tax-export-report",children:[e.jsx(tt,{}),e.jsxs("div",{className:"rounded-lg border border-border/15 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx(ne,{className:"w-4 h-4 text-foreground/70"}),e.jsx("h3",{className:"text-[16px] font-display font-light tracking-tight",children:"Income transactions"})]}),e.jsx("p",{className:"text-[13px] text-foreground/65 leading-relaxed mb-4",children:"One row per payment received, with gratuity, sales tax, and payment method broken out. Use it for bookkeeping review or hand it to your accountant for income reporting."}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[12px] tracking-[0.12em] uppercase text-foreground/70 mb-1",children:"From"}),e.jsx(q,{type:"date",value:l,onChange:d=>n(d.target.value),className:"h-9 w-[150px] text-[13px]","data-testid":"input-transactions-from"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[12px] tracking-[0.12em] uppercase text-foreground
5/70 mb-1",children:"To"}),e.jsx(q,{type:"date",value:i,onChange:d=>a(d.target.value),className:"h-9 w-[150px] text-[13px]","data-testid":"input-transactions-to"})]}),e.jsxs(X,{onClick:F,disabled:t||!l||!i,"data-testid":"button-export-transactions",children:[e.jsx(_,{className:"w-3.5 h-3.5"}),t?"Exporting...":"Export CSV"]})]})]}),e.jsxs("div",{className:"rounded-lg border border-border/15 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx(ve,{className:"w-4 h-4 text-foreground/70"}),e.jsx("h3",{className:"text-[16px] font-display font-light tracking-tight",children:"Contractor payments (1099)"})]}),e.jsx("p",{className:"text-[13px] text-foreground/65 leading-relaxed mb-3",children:"Money you paid out for the tax year, grouped by who you paid, to help prepare 1099s. Mark expenses with the âContractor payment (1099)â toggle so this exports your actual 1099 list."}),e.jsx("div",{className:"rounded-md bg-amber-50 border border-amber-200/70 p-3 mb-4",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(J,{className:"w-3.5 h-3.5 text-amber-600 mt-0.5 shrink-0"}),e.jsx("p",{className:"text-[12px] text-amber-900/80 leading-relaxed",children:"Colara does not store contractor tax IDs (W-9 or TIN) or confirm who needs a 1099. Use this to get a head start, then collect a W-9 and confirm each contractor's status and totals before filing."})]})}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[12px] tracking-[0.12em] uppercase text-foreground/70 mb-1",children:"Tax year"}),e.jsxs(O,{value:c,onValueChange:u,children:[e.jsx(V,{className:"h-9 w-[120px] text-[13px]","data-testid":"select-tax-year",children:e.jsx(G,{})}),e.jsx(Y,{children:b.map(d=>e.jsx(R,{value:d,children:d},d))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[12px] tracking-[0.12em] uppercase text-foreground/70 mb-1",children:"Include"}),e.jsxs(O,{value:m,onValueChange:d=>v(d),children:[e.jsx(V,{className:"h-9 w-[200px] text-[13px]","data-testid":"select-1099-scope",children:e.jsx(G,{})}),e.jsxs(Y,{children:[e.jsx(R,{value:"tagged",children:"Tagged contractor payments"}),e.jsx(R,{value:"all",children:"All expenses by payee"})]})]})]}),e.jsxs(X,{onClick:L,disabled:h,"data-testid":"button-export-1099",children:[e.jsx(_,{className:"w-3.5 h-3.5"}),h?"Exporting...":"Export CSV"]})]})]}),e.jsx("p",{className:"text-[12px] text-foreground/65 leading-relaxed",children:"Every file here is a plain CSV, ready for category review, reconciliation, and handoff to your bookkeeper or accountant."})]})}function hs(){const{toast:s}=H(),{reportType:r,selectReportType:l}=rt(),[n,i]=j.useState("ytd"),[a,t]=j.useState(""),[o,c]=j.useState(""),[u,h]=j.useState(!1),[x,m]=j.useState(!1),{data:v}=T({queryKey:["/api/crm/settings"]}),b=n==="custom"?{from:a,to:o}:n==="all"?{from:"",to:""}:Ue(n),F=[{key:"profit-loss",label:"Profit & Loss",icon:we},{key:"client-profitability",label:"Client & Event",icon:ve},{key:"income",label:"Income",icon:oe},{key:"expenses",label:"Expenses",icon:ee},{key:"receivables",label:"Receivables",icon:Ye},{key:"pipeline",label:"Pipeline",icon:He},{key:"lead-sources",label:"Lead Sources",icon:Ke},{key:"sales-tax",label:"Sales Tax",icon:Ne},{key:"tax-export",label:"Tax Exports",icon:ne},{key:"analytics",label:"Analytics",icon:We}],L=["profit-loss","client-profitability","income","expenses","sales-tax","lead-sources"].includes(r),d=r!=="tax-export"&&r!=="analytics",E=async()=>{h(!0);try{const N=new URLSearchParams;b.from&&N.set("from",b.from),b.to&&N.set("to",b.to);const S=N.toString()?`?${N.toString()}`:"",g={"profit-loss":"profit-loss","client-profitability":"client-profitability",income:"income",expenses:"expenses",receivables:"receivables",pipeline:"sales-pipeline","lead-sources":"lead-sources","sales-tax":"sales-tax"};N.set("export","true");const $=N.toString()?`?${N.toString()}`:"",k=`/api/crm/reports/${g[r]}${$}`,W=await w("GET",k);if(!W.ok)throw new Error("Failed to fetch report data");const te=await W.json();ct(r,te,b),s({title:"Report exported as CSV"})}catch{s({title:"Export failed",variant:"destructive"})}finally{h(!1)}},D=async()=>{m(!0);try{if(r==="analytics"||r==="tax-export")return;const{printReport:N}=await Ee(async()=>{const{printReport:S}=await import("./printReport-CsuYo3G5.js");return{printReport:S}},__vite__mapDeps([0,1,2,3]));await N({reportType:r,dates:b,businessName:v?.businessName||null,logoUrl:v?.logoUrl||null})}catch{s({title:"Failed to generate report",variant:"destructive"})}finally{m(!1)}};return e.jsxs("div",{className:"space-y-8","data-testid":"financials-view",children:[e.jsx(Ae,{title:"What is this?",description:"Your Financials view gives you a clear picture of your business revenue â total earned, outstanding payments, and upcoming invoices. Know exactly where your money stands at any time.",guideSlug:"analytics",storageKey:"crm-financials",steps:["Review your revenue summary â total invoiced, paid, and outstanding.","Click any entry to see the associated invoice and client details.","Export your financial data for tax preparation or bookkeeping."]}),e.jsxs("div",{className:"flex items-end justify-between flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[12px] tracking-[0.35em] uppercase text-foreground
5/70 font-medium mb-3",children:"Analytics"}),e.jsx("h2",{className:"text-xl font-display font-light tracking-tight",children:"Financial Reports"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[L&&e.jsx(lt,{preset:n,setPreset:i,customFrom:a,setCustomFrom:t,customTo:o,setCustomTo:c}),d&&e.jsxs("div",{className:"flex items-center gap-1.5 ml-2",children:[e.jsxs("button",{onClick:E,disabled:u,className:"flex items-center gap-1.5 px-3 py-1.5 text-[12px] tracking-[0.12em] uppercase text-foreground/70 hover:text-foreground transition-colors border border-border/15 rounded disabled:opacity-30","data-testid":"button-export-csv",title:"Export as CSV",children:[e.jsx(_,{className:"w-3 h-3"}),u?"Exporting...":"CSV"]}),e.jsxs("button",{onClick:D,disabled:x,className:"flex items-center gap-1.5 px-3 py-1.5 text-[12px] tracking-[0.12em] uppercase text-foreground/70 hover:text-foreground transition-colors border border-border/15 rounded disabled:opacity-30","data-testid":"button-print-report",title:"Print / Save as PDF",children:[e.jsx(Ge,{className:"w-3 h-3"}),x?"Loading...":"PDF"]})]})]})]}),e.jsx("div",{className:"flex items-center gap-1 border-b border-border/15 pb-px",children:F.map(N=>{const S=N.icon;return e.jsxs("button",{onClick:()=>l(N.key),className:`flex items-center gap-1.5 px-4 py-2.5 text-[12px] tracking-[0.08em] font-medium transition-colors border-b-2 -mb-px ${r===N.key?"border-foreground
5/60 text-foreground":"border-transparent text-foreground/65 hover:text-foreground/65"}`,"data-testid":`report-tab-${N.key}`,children:[e.jsx(S,{className:"w-3.5 h-3.5"}),N.label]},N.key)})}),r==="profit-loss"&&e.jsx(xt,{dates:b}),r==="client-profitability"&&e.jsx(nt,{dates:b}),r==="income"&&e.jsx(mt,{dates:b}),r==="expenses"&&e.jsx(pt,{dates:b}),r==="receivables"&&e.jsx(ut,{}),r==="pipeline"&&e.jsx(gt,{}),r==="lead-sources"&&e.jsx(ht,{dates:b}),r==="sales-tax"&&e.jsx(ze,{dates:b}),r==="tax-export"&&e.jsx(wt,{}),r==="analytics"&&e.jsx(vt,{})]})}export{us as EmailLogView,hs as FinancialsView};
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.