PageSourceSearch

https://portal.wavespestcontrol.com/assets/TaxPage-DKzju8Qj.js

js wavespestcontrol.com collected 2026-10-06 18:18:26 UTC 104,007 bytes, 5 lines download raw bytes

1import{x as be,r as s,bi as bn,aJ as Sn,bk as wn,aH as Cn,bl as kn,X as An,j as e,aq as Dn,cs as Bn,a7 as E,aE as In,ct as zn,cu as _n,b3 as Pn,f as je,m as Fn,a8 as X,ae,a9 as $e,ac as Ln}from"./index-C7xls3vf.js";import{F as O}from"./Field-QtCkUj3T.js";import{A as K}from"./ActionFeedback-CYBNb5NL.js";import{B as te}from"./Badge-CVjSA8_n.js";import{C as M}from"./Card-BfSuAWwh.js";import{T as Pe,a as Fe,b as fe,c as ye,d as Le,e as V}from"./Table-74yw4geW.js";import{A as On}from"./AdminCommandHeader-BFz5Ixil.js";import{L as Nn}from"./list-checks-BMdY-TED.js";import{P as Wn}from"./percent-DfV-OVdK.js";import{C as Mn}from"./calendar-days-CVgvsFK_.js";function me(a,i,r){const[S,o]=s.useState(0),[f,x]=s.useState(!0),[$,m]=s.useState(""),B=s.useCallback(()=>o(N=>N+1),[]);return s.useEffect(()=>{let N=!0;return x(!0),m(""),F(a).then(p=>{N&&i(r?p[r]||[]:p)}).catch(p=>{N&&m(p.message||"Request failed")}).finally(()=>{N&&x(!1)}),()=>{N=!1}},[a,i,r,S]),{loading:f,error:$,retry:B}}function ve({read:a,label:i}){return e.jsx("div",{className:"min-h-60 py-6",children:e.jsx(K,{error:!!a.error,onRetry:a.error?a.retry:void 0,children:a.error?"Could not load "+i+": "+a.error:"Loading "+i+"…"})})}const Ye="/api";function F(a,i={}){return fetch(`${Ye}${a}`,{headers:{Authorization:`Bearer ${localStorage.getItem("waves_admin_token")}`,"Content-Type":"application/json"},...i}).then(async r=>{var S;if(!r.ok){let o="";try{o=((S=await r.json())==null?void 0:S.error)||""}catch{}throw new Error(o||`HTTP ${r.status}`)}return r.json()})}function Y({label:a,value:i,color:r,sub:S,onClick:o}){const f=be(640),x=o?E:M;return e.jsxs(x,{variant:"secondary",className:"!block !h-auto text-left whitespace-normal",onClick:o,style:{padding:f?"12px 10px":"16px 20px",flex:f?"1 1 calc(50% - 6px)":"1 1 0",minWidth:f?0:140,cursor:o?"pointer":"default",transition:"border-color 0.15s"},onMouseEnter:$=>{o&&($.currentTarget.style.borderColor=r||"#18181B")},onMouseLeave:$=>{$.currentTarget.style.borderColor="#E4E4E7"},children:[" ",e.jsx("div",{style:{color:"#71717A",fontSize:14,marginBottom:6},children:a})," ",e.jsx("div",{className:"u-nums",style:{fontSize:22,fontWeight:500,color:r||"#09090B"},children:i}),S&&e.jsx("div",{style:{fontSize:14,color:"#71717A",marginTop:4},children:S})]})}const Z=a=>a?Fn(a):"—",A=a=>a!=null?"$"+Number(a).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2}):"—",Te=a=>a!=null?(a*100).toFixed(2)+"%":"—",we=a=>{if(!a)return 0;const i=String(a).slice(0,10),r=je();return Math.floor((new Date(i+"T00:00:00Z")-new Date(r+"T00:00:00Z"))/864e5)},Ue={high:"#C8312F",medium:"#52525B",low:"#18181B"},Tn={upcoming:"#18181B",prepared:"#52525B",filed:"#18181B",paid:"#18181B",late:"#C8312F",new:"#18181B",reviewed:"#52525B",acted_on:"#18181B",dismissed:"#71717A"},Un=["upcoming","prepared","filed","paid","late"],qn=[{key:"overview",label:"Overview",Icon:bn},{key:"rates",label:"Rates",Icon:Wn},{key:"services",label:"Taxability",Icon:Sn},{key:"exemptions",label:"Exemptions",Icon:In},{key:"equipment",label:"Equipment",Icon:Cn},{key:"expenses",label:"Expenses",Icon:Nn},{key:"bankimport",label:"Import",Icon:zn},{key:"mileage",label:"Mileage",Icon:_n},{key:"revenue",label:"Revenue",Icon:wn},{key:"pnl",label:"P&L",Icon:kn},{key:"filings",label:"Filings",Icon:Mn},{key:"advisor",label:"Advisor",Icon:Pn},{key:"exports",label:"Exports",Icon:An},{key:"ar",label:"A/R",Icon:Bn}],yn=[{key:"overview",label:"Overview",Icon:bn,tabs:["overview"]},{key:"setup",label:"Setup",Icon:Sn,tabs:["rates","services","exemptions"]},{key:"expenses",label:"Expenses",Icon:Nn,tabs:["expenses"]},{key:"revenue",label:"Revenue",Icon:wn,tabs:["revenue"]},{key:"assets",label:"Assets",Icon:Cn,tabs:["equipment","mileage"]},{key:"reports",label:"Reports",Icon:kn,tabs:["pnl","filings","advisor"]},{key:"compliance",label:"Compliance",Icon:An,tabs:["exports","ar"]}],Yn=Object.fromEntries(qn.map(a=>[a.key,a]));function Vn(){const a=be(640),[i,r]=s.useState([]),S=me("/admin/tax/rates",r,"rates");return S.loading||S.error?e.jsx(ve,{read:S,label:"tax rates"}):e.jsxs("div",{children:[" ",e.jsx("h2",{style:{fontSize:18,fontWeight:500,color:"#09090B",marginBottom:12},children:"Florida Sales Tax Rates by County"})," ",i.length===0&&e.jsx(M,{className:"p-6 text-zinc-500",children:"No tax rates are available."}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:a?"1fr":"repeat(auto-fill, minmax(280px, 1fr))",gap:10},children:i.filter(o=>o.status==="current").map(o=>e.jsxs(M,{style:{padding:"14px 16px"},children:[" ",e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8},children:[" ",e.jsxs("span",{style:{fontSize:15,fontWeight:500,color:"#09090B"},children:[o.county," County"]})," ",e.jsx("span",{className:"u-nums",style:{fontSize:18,fontWeight:500,color:"#18181B"},children:Te(o.combinedRate)})," "]})," ",e.jsxs("div",{style:{fontSize:14,color:"#71717A",marginBottom:4},children:["State: ",Te(o.stateRate)," + County surtax:"," ",Te(o.countySurtax)]})," ",e.jsxs("div",{style:{fontSize:14,color:"#71717A"},children:["Zone: ",o.serviceZone]})," ",e.jsxs("div",{style:{fontSize:14,color:"#71717A",marginTop:4},children:["Effective: ",Z(o.effectiveDate)]}),o.notes&&e.jsx("div",{style:{fontSize:14,color:"#71717A",marginTop:4},children:o.notes})]},o.id))}),i.filter(o=>o.status==="staged").length>0&&e.jsxs("div",{style:{marginTop:20},children:[" ",e.jsx("div",{style:{fontSize:14,color:"#71717A",marginBottom:8},children:"Staged Rates (not yet in effect)"}),i.filter(o=>o.status==="staged").map(o=>e.jsxs(M,{style:{display:"flex",gap:12,padding:"6px 12px",fontSize:14,color:"#71717A",marginBottom:3},children:[" ",e.jsx("span",{children:o.county}),e.jsx("span",{className:"u-nums",style:{},children:Te(o.combinedRate)})," ",e.jsxs("span",{children:["Effective ",Z(o.effectiveDate)]})," "]},o.id))]}),i.filter(o=>o.status==="superseded").length>0&&e.jsxs("div",{style:{marginTop:20},children:[" ",e.jsx("div",{style:{fontSize:14,color:"#71717A",marginBottom:8},children:"Historical Rates"}),i.filter(o=>o.status==="superseded").map(o=>e.jsxs(M,{style:{display:"flex",gap:12,padding:"6px 12px",fontSize:14,color:"#71717A",marginBottom:3,opacity:.6},children:[" ",e.jsx("span",{children:o.county}),e.jsx("span",{className:"u-nums",style:{},children:Te(o.combinedRate)})," ",e.jsxs("span",{children:[Z(o.effectiveDate)," — ",Z(o.expiryDate)]})," "]},o.id))]})]})}function Hn(){const a=s.useRef(!1),[i,r]=s.useState(""),[S,o]=s.useState(""),[f,x]=s.useState([]),$=me("/admin/tax/service-taxability",x,"services"),[m,B]=s.useState(null),N=async p=>{if(!a.current){a.current=!0,r("toggleTaxable"),o("");try{const l=p.isTaxable?"EXEMPT":"TAXABLE";if(!window.confirm(`Mark "${p.serviceLabel}" as ${l} for FL sales tax? This changes the tax determination used going forward.`))return;B(p.id);try{await F(`/admin/tax/service-taxability/${p.id}`,{method:"PUT",body:JSON.stringify({isTaxable:!p.isTaxable})}),x(y=>y.map(h=>h.id===p.id?{...h,isTaxable:!h.isTaxable}:h))}catch(y){o("Failed to update: "+(y.message||"Unknown error"))}B(null)}finally{a.current=!1,r("")}}};return $.loading||$.error?e.jsx(ve,{read:$,label:"service taxability"}):e.jsxs("div",{children:[S&&e.jsx(K,{error:!0,className:"mb-4 whitespace-pre-wrap",children:S})," ",e.jsx("h2",{style:{fontSize:18,fontWeight:500,color:"#09090B",marginBottom:4},children:"Service Taxability Matrix"})," ",e.jsx("div",{style:{fontSize:14,color:"#71717A",marginBottom:14}
1,children:"Click a service to toggle FL sales tax collection"}),f.length===0&&e.jsx(M,{className:"p-6 text-zinc-500",children:"No service taxability records are available."}),f.map(p=>e.jsxs(E,{onClick:()=>N(p),style:{display:"flex",alignItems:"center",gap:12,padding:"10px 14px",marginBottom:4,cursor:"pointer",opacity:m===p.id?.5:1},variant:"secondary",className:"!flex flex-wrap !h-auto w-full text-left whitespace-normal",type:"button",disabled:!!i,children:[" ",e.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:p.isTaxable?"#18181B":"#71717A",flexShrink:0}})," ",e.jsxs("div",{style:{flex:1},children:[" ",e.jsx("span",{style:{fontSize:14,fontWeight:500,color:"#09090B"},children:p.serviceLabel})," ",e.jsx("span",{style:{fontSize:14,color:"#71717A",marginLeft:8},children:p.serviceKey})," "]})," ",e.jsx(te,{tone:"neutral",children:p.isTaxable?"Taxable":"Exempt"}),p.taxCategory&&e.jsx(te,{tone:"neutral",children:p.taxCategory}),p.flStatuteRef&&e.jsx("span",{style:{fontSize:14,color:"#71717A"},children:p.flStatuteRef})]},p.id))]})}function Gn(){const a=s.useRef(!1),[i,r]=s.useState(""),[S,o]=s.useState(""),[f,x]=s.useState([]),$=me("/admin/tax/equipment",x,"equipment"),m=$.retry,[B,N]=s.useState(!1),p={name:"",assetCategory:"equipment",purchaseDate:"",purchaseCost:"",depreciationMethod:"section_179",usefulLifeYears:"7",makeModel:"",businessUsePct:"100",luxuryAutoExempt:!1},[l,y]=s.useState(p),h=async(n,b)=>{if(!a.current){a.current=!0,r("confirmVehicleUse"),o("");try{const P=window.prompt("Business-use % for this vehicle (0–100)? This confirms it so depreciation computes.",String(b??100));if(P==null)return;const z=Number(P);if(!Number.isFinite(z)||z<0||z>100){alert("Enter a number between 0 and 100.");return}const Q=window.confirm("Is this vehicle EXEMPT from the IRS §280F passenger-auto depreciation limits (heavy vehicle, >6,000 lb GVWR)? OK = exempt (full MACRS); Cancel = not exempt (leave $0 for CPA-capped calc).");try{await F(`/admin/tax/equipment/${n}`,{method:"PUT",body:JSON.stringify({businessUsePct:z,luxuryAutoExempt:Q})}),m()}catch(_){o("Failed: "+_.message)}}finally{a.current=!1,r("")}}},T=async()=>{if(!a.current){a.current=!0,r("handleAdd"),o("");try{if(!l.name||!l.purchaseCost)return;try{await F("/admin/tax/equipment",{method:"POST",body:JSON.stringify({...l,purchaseCost:parseFloat(l.purchaseCost),usefulLifeYears:parseInt(l.usefulLifeYears),section179Elected:l.depreciationMethod==="section_179",businessUsePct:l.assetCategory==="vehicle"?Number(l.businessUsePct):void 0,luxuryAutoExempt:l.assetCategory==="vehicle"?l.luxuryAutoExempt:void 0})}),N(!1),y(p);const n=await F("/admin/tax/equipment");x(n.equipment||[])}catch(n){o("Failed: "+n.message)}}finally{a.current=!1,r("")}}},v=f.filter(n=>n.active).reduce((n,b)=>n+b.purchaseCost,0),g=f.filter(n=>n.active).reduce((n,b)=>n+b.currentBookValue,0),d=f.filter(n=>n.active).reduce((n,b)=>n+b.accumulatedDepreciation,0);return $.loading||$.error?e.jsx(ve,{read:$,label:"equipment"}):e.jsxs("div",{children:[S&&e.jsx(K,{error:!0,className:"mb-4 whitespace-pre-wrap",children:S})," ",e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:14},children:[" ",e.jsxs("div",{children:[" ",e.jsx("h2",{style:{fontSize:18,fontWeight:500,color:"#09090B"},children:"Equipment & Depreciation Register"})," ",e.jsx("div",{style:{fontSize:14,color:"#71717A"},children:"Section 179 & MACRS tracking"})," "]})," ",e.jsx(E,{onClick:()=>N(!B),type:"button",variant:"primary",className:"min-w-11",disabled:!!i,children:"+ Add Equipment"})," "]}),e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:10,marginBottom:14},children:[" ",e.jsx(Y,{label:"Total Cost",value:A(v)})," ",e.jsx(Y,{label:"Book Value",value:A(g),color:"#18181B"})," ",e.jsx(Y,{label:"Depreciated",value:A(d),color:"#52525B"})," "]}),B&&e.jsxs("div",{style:{background:"#F4F4F5",border:"1px solid #18181B44",borderRadius:10,padding:14,marginBottom:12,display:"flex",gap:8,flexWrap:"wrap",alignItems:"end"},children:[" ",e.jsx("div",{children:e.jsx(O,{label:"Name *",className:"min-w-0",children:e.jsx(X,{value:l.name,onChange:n=>y(b=>({...b,name:n.target.value})),style:{width:180},disabled:!!i})})})," ",e.jsx("div",{children:e.jsx(O,{label:"Make/Model",className:"min-w-0",children:e.jsx(X,{value:l.makeModel,onChange:n=>y(b=>({...b,makeModel:n.target.value})),style:{width:150},disabled:!!i})})})," ",e.jsxs("div",{children:[" ",e.jsx(O,{label:"Category",className:"min-w-0",children:e.jsxs(ae,{value:l.assetCategory,onChange:n=>y(b=>({...b,assetCategory:n.target.value,usefulLifeYears:n.target.value==="vehicle"?"5":b.usefulLifeYears})),style:{minWidth:100},disabled:!!i,children:[" ",e.jsx("option",{value:"vehicle",children:"Vehicle"}),e.jsx("option",{value:"equipment",children:"Equipment"}),e.jsx("option",{value:"tool",children:"Tool"}),e.jsx("option",{value:"technology",children:"Technology"})," "]})})]})," ",e.jsx("div",{children:e.jsx(O,{label:"Purchase Date",className:"min-w-0",children:e.jsx(X,{type:"date",value:l.purchaseDate,onChange:n=>y(b=>({...b,purchaseDate:n.target.value})),style:{width:130},disabled:!!i})})})," ",e.jsx("div",{children:e.jsx(O,{label:"Cost *",className:"min-w-0",children:e.jsx(X,{type:"number",step:"0.01",value:l.purchaseCost,onChange:n=>y(b=>({...b,purchaseCost:n.target.value})),style:{width:90},disabled:!!i})})})," ",e.jsxs("div",{children:[" ",e.jsx(O,{label:"Method",className:"min-w-0",children:e.jsxs(ae,{value:l.depreciationMethod,onChange:n=>y(b=>({...b,depreciationMethod:n.target.value})),style:{minWidth:110},disabled:!!i,children:[" ",e.jsx("option",{value:"section_179",children:"Section 179"}),e.jsx("option",{value:"MACRS",children:"MACRS"}),e.jsx("option",{value:"SL",children:"Straight Line"}),e.jsx("option",{value:"bonus_100",children:"100% Bonus"})," "]})})]})," ",(l.depreciationMethod==="MACRS"||l.assetCategory==="vehicle")&&e.jsxs("div",{children:[" ",e.jsx(O,{label:"Recovery life",className:"min-w-0",children:e.jsxs(ae,{value:l.usefulLifeYears,onChange:n=>y(b=>({...b,usefulLifeYears:n.target.value})),style:{minWidth:90},disabled:!!i,children:[" ",e.jsx("option",{value:"3",children:"3-year"}),e.jsx("option",{value:"5",children:"5-year"}),e.jsx("option",{value:"7",children:"7-year"})," "]})})]})," ",l.assetCategory==="vehicle"&&e.jsxs("div",{children:[" ",e.jsx(O,{label:"Business use %",className:"min-w-0",children:e.jsx(X,{type:"number",min:"0",max:"100",value:l.businessUsePct,onChange:n=>y(b=>({...b,businessUsePct:n.target.value})),style:{width:90},disabled:!!i})})]})," ",l.assetCategory==="vehicle"&&e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:14,color:"#71717A"},className:"ui-choice-label",children:[e.jsx($e,{type:"checkbox",checked:l.luxuryAutoExempt,onChange:n=>y(b=>({...b,luxuryAutoExempt:n.target.checked})),disabled:!!i}),"§280F-exempt (heavy, >6,000 lb)"]})," ",e.jsx(E,{onClick:T,type:"button",variant:"primary",className:"min-w-11",disabled:!!i,loading:i==="handleAdd",children:"Save"})," ",e.jsx(E,{onClick:()=>N(!1),type:"button",variant:"secondary",className:"min-w-11",disabled:!!i,children:"Cancel"})," "]}),!f.some(n=>n.active)&&e.jsx(M,{className:"p-6 text-zinc-500",children:"No equipment recorded. Use Add Equipment to record an asset."}),f.filter(n=>n.active).map(n=>e.jsxs(M,{style:{padding:"12px 14px",marginBottom:4},children:[" ",e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginBottom:6},children:[" ",e.jsx("span",{style:{fontSize:14,fontWeight:500,color:"#09090B",flex:1},children:n.name})," ",e.jsx(te,{tone:"neutral",children:n.assetCategory})," ",e.jsx(te,{tone:"neutral",children:n.depreciationMethod})," ",n.assetCategory==="vehicle"&&!(n.businessUseConfirmed&&n.luxuryAutoExempt)&&e.jsx(E,{onClick:()=>h(n.id,n.businessUsePct),title:"Depreciation won't compute until business use and §280F exemption are confirmed",type:"button",variant:"secondary",className:"min-w-11",disabled:!!i,children:"Confirm for depreciation"})," ",n.assetCategory==="vehicle"&&n.businessUseConfirmed&&n.luxuryAutoExempt&&e.jsxs("span",{style:{fontSize:14,color:"#71717A"},children:[n.businessUsePct,"% business · §280F-exempt"]})," "]})," ",e.jsxs("div",{style:{display:"flex",gap:16,fontSize:14,color:"#71717A",flexWrap:"wrap"},children:[n.makeModel&&e.jsx("span",{children:n.makeModel}),e.jsxs("span",{children:["Cost:"," ",e.jsx("span",{className:"u-nums",style:{color:"#27272A"},children:A(n.purchaseCost)})]})," ",e.jsxs("span",{children:["Book:"," ",e.jsx("span",{className:"u-nums",style:{color:"#18181B"},children:A(n.currentBookValue)})]})," ",e.jsxs("span",{children:["Depr:"," ",e.jsx("span",{className:"u-nums",style:{color:"#52525B"},children:A(n.accumulatedDepreciation)})]}),n.irsClass&&e.jsxs("span",{children:["IRS: ",n.irsClass]}),e.jsxs("span",{children:["Purchased: ",Z(n.purchaseDate)]})," "]})," "]},n.id))]})}function Jn(){var I;const a=s.useRef(!1),[i,r]=s.useState(""),[S,o]=s.useState(""),f=s.useRef(0),[x,$]=s.useState(!0),[m,B]=s.useState(""),[N,p]=s.useState([]),[l,y]=s.useState([]),[h,T]=s.useState([]),[v,g]=s.useState(!1),[d,n]=s.useState({categoryId:"",description:"",amount:"",expenseDate:"",vendorName:"",paymentMethod:"card"}),[b,P]=s.useState(String(new Date().getFullYear())),[z,Q]=s.useState(!1),[_,H]=s.useState(!1),G=((I=h.find(u=>!u.category))==null?void 0:I.count)||0,J=async()=>
1{if(!a.current){a.current=!0,r("runAutoCategorize"),o("");try{if(!window.confirm(`AI-categorize up to 20 of the ${G} uncategorized ${b} expenses into Schedule C categories? Each pick is recorded and reviewable — run again to continue through the backlog.`))return;Q(!0);try{const u=await F("/admin/tax/expenses/auto-categorize",{method:"POST",body:JSON.stringify({limit:20,year:b})});alert(`Categorized ${u.applied} of ${u.processed} — ${u.remaining} uncategorized remaining${u.remaining>0?" (run again to continue)":""}`),c()}catch(u){o(`Auto-categorize failed: ${u.message}`)}Q(!1)}finally{a.current=!1,r("")}}},c=s.useCallback(async()=>{const u=++f.current;$(!0),B("");try{const[C,k]=await Promise.all([F(`/admin/tax/expenses?year=${b}`),F("/admin/tax/expense-categories")]);if(u!==f.current)return;p(C.expenses||[]),T(C.summary||[]),y(k.categories||[])}catch(C){u===f.current&&B(C.message)}finally{u===f.current&&$(!1)}},[b]);s.useEffect(()=>{c()},[c]);const q=async()=>{if(!a.current){a.current=!0,r("handleAdd"),o("");try{if(!d.description||!d.amount||!d.expenseDate||_)return;H(!0);try{await F("/admin/tax/expenses",{method:"POST",body:JSON.stringify({...d,amount:parseFloat(d.amount)})}),g(!1),n({categoryId:"",description:"",amount:"",expenseDate:"",vendorName:"",paymentMethod:"card"}),c()}catch(u){o("Failed: "+u.message)}finally{H(!1)}}finally{a.current=!1,r("")}}},R=h.reduce((u,C)=>u+C.total,0),j=h.reduce((u,C)=>u+C.deductible,0);return x||m?e.jsx(ve,{read:{loading:x,error:m,retry:c},label:"expenses"}):e.jsxs("div",{children:[S&&e.jsx(K,{error:!0,className:"mb-4 whitespace-pre-wrap",children:S})," ",e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:14},children:[" ",e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[" ",e.jsx(O,{label:"Business Expenses",className:"min-w-0",children:e.jsxs(ae,{value:b,onChange:u=>P(u.target.value),style:{minWidth:80},disabled:!!i,children:[" ",Array.from({length:new Date().getFullYear()-2023},(u,C)=>String(new Date().getFullYear()-C)).map(u=>e.jsx("option",{value:u,children:u},u))," "]})})," "]})," ",G>0&&e.jsx(E,{onClick:J,disabled:!!i||z,type:"button",variant:"secondary",loading:z,className:"min-w-11",children:`AI-categorize (${G} uncategorized shown)`})," ",e.jsx(E,{onClick:()=>g(!v),type:"button",variant:"primary",className:"min-w-11",disabled:!!i,children:"+ Add Expense"})," "]})," ",e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:10,marginBottom:14},children:[" ",e.jsx(Y,{label:"Total Expenses",value:A(R)})," ",e.jsx(Y,{label:"Tax Deductible",value:A(j),color:"#18181B"})," ",e.jsx(Y,{label:"Records",value:N.length,color:"#18181B"})," "]}),v&&e.jsxs("div",{style:{background:"#F4F4F5",border:"1px solid #18181B44",borderRadius:10,padding:14,marginBottom:12,display:"flex",gap:8,flexWrap:"wrap",alignItems:"end"},children:[" ",e.jsxs("div",{children:[" ",e.jsx(O,{label:"Category",className:"min-w-0",children:e.jsxs(ae,{value:d.categoryId,onChange:u=>n(C=>({...C,categoryId:u.target.value})),style:{minWidth:160},disabled:!!i,children:[" ",e.jsx("option",{value:"",children:"Select..."}),l.map(u=>e.jsxs("option",{value:u.id,children:[u.name," (Line ",u.irsLine,")"]},u.id))]})})]})," ",e.jsx("div",{children:e.jsx(O,{label:"Description *",className:"min-w-0",children:e.jsx(X,{value:d.description,onChange:u=>n(C=>({...C,description:u.target.value})),style:{width:200},disabled:!!i})})})," ",e.jsx("div",{children:e.jsx(O,{label:"Amount *",className:"min-w-0",children:e.jsx(X,{type:"number",step:"0.01",value:d.amount,onChange:u=>n(C=>({...C,amount:u.target.value})),style:{width:90},disabled:!!i})})})," ",e.jsx("div",{children:e.jsx(O,{label:"Date *",className:"min-w-0",children:e.jsx(X,{type:"date",value:d.expenseDate,onChange:u=>n(C=>({...C,expenseDate:u.target.value})),style:{width:130},disabled:!!i})})})," ",e.jsx("div",{children:e.jsx(O,{label:"Vendor",className:"min-w-0",children:e.jsx(X,{value:d.vendorName,onChange:u=>n(C=>({...C,vendorName:u.target.value})),style:{width:130},disabled:!!i})})})," ",e.jsx(E,{onClick:q,disabled:!!i||_,type:"button",variant:"primary",className:"min-w-11",loading:i==="handleAdd",children:_?"Saving…":"Save"})," ",e.jsx(E,{onClick:()=>g(!1),type:"button",variant:"secondary",className:"min-w-11",disabled:!!i,children:"Cancel"})," "]}),h.length>0&&e.jsxs("div",{style:{marginBottom:16},children:[" ",e.jsx("div",{style:{fontSize:14,color:"#71717A",marginBottom:8},children:"By Schedule C Category"}),h.map((u,C)=>e.jsxs(M,{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 12px",marginBottom:3},children:[" ",e.jsx("span",{style:{fontSize:14,color:"#09090B",fontWeight:500,flex:1},children:u.category||"Uncategorized"})," ",e.jsx("span",{className:"u-nums",style:{fontSize:14,color:"#27272A"},children:A(u.total)})," ",e.jsxs("span",{className:"u-nums",style:{fontSize:14,color:"#18181B"},children:[A(u.deductible)," deductible"]})," ",e.jsxs("span",{style:{fontSize:14,color:"#71717A"},children:[u.count," items"]})," "]},C))]}),N.map(u=>e.jsxs(M,{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",marginBottom:3},children:[" ",e.jsx("span",{style:{fontSize:14,color:"#71717A",minWidth:70},children:Z(u.expenseDate)})," ",e.jsx("span",{style:{fontSize:14,color:"#09090B",flex:1},children:u.description}),u.categoryName&&e.jsx(te,{tone:"neutral",children:u.categoryName}),u.vendorName&&e.jsx("span",{style:{fontSize:14,color:"#71717A"},children:u.vendorName}),e.jsx("span",{className:"u-nums",style:{fontSize:14,fontWeight:500,color:"#27272A"},children:A(u.amount)})," "]},u.id)),N.length===0&&e.jsxs("div",{style:{padding:30,textAlign:"center",color:"#71717A",fontSize:14},children:["No expenses recorded for ",b,"."]})]})}function Kn(){const a=s.useRef(!1),[i,r]=s.useState(""),[S,o]=s.useState(""),[f,x]=s.useState([]),$=me("/admin/tax/filings",x,"filings"),m=$.retry,B=async(l,y)=>{if(!a.current){a.current=!0,r("handleStatusChange"),o("");try{try{const h={status:y};if(y==="filed"&&(h.filedDate=je()),y==="paid"){h.paidDate=je();const T=f.find(d=>d.id===l),v=window.prompt("Amount paid (required — credits future estimates):",(T==null?void 0:T.amountDue)!=null?String(T.amountDue):"");if(v===null)return;const g=Number(v);if(v.trim()===""||!Number.isFinite(g)||g<0)return alert("Enter a valid non-negative amount — a filing cannot be marked paid without one.");h.amountPaid=g}await F(`/admin/tax/filings/${l}`,{method:"PUT",body:JSON.stringify(h)}),m()}catch(h){o("Failed: "+h.message)}}finally{a.current=!1,r("")}}},N=f.filter(l=>l.status==="upcoming"||l.status==="prepared"),p=f.filter(l=>l.status==="filed"||l.status==="paid");return $.loading||$.error?e.jsx(ve,{read:$,label:"filings"}):e.jsxs("div",{children:[S&&e.jsx(K,{error:!0,className:"mb-4 whitespace-pre-wrap",children:S})," ",e.jsx("h2",{style:{fontSize:18,fontWeight:500,color:"#09090B",marginBottom:14},children:"Tax Filing Calendar"}),e.jsx("div",{style:{fontSize:14,color:"#71717A",marginBottom:8},children:"Upcoming Deadlines"}),N.length===0&&e.jsx("div",{style:{padding:20,textAlign:"center",color:"#71717A",fontSize:14,marginBottom:16},children:"All caught up!"}
1),N.map(l=>{const y=we(l.dueDate),h=y<=7?"#C8312F":y<=30?"#52525B":"#71717A";return e.jsxs(M,{style:{padding:"12px 14px",marginBottom:6},children:[" ",e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginBottom:6},children:[" ",e.jsx("span",{style:{fontSize:14,fontWeight:500,color:"#09090B",flex:1},children:l.title})," ",e.jsx(te,{tone:Tn[l.status]==="#C8312F"?"alert":"neutral",children:l.status})," ",e.jsx("span",{className:"u-nums",style:{fontSize:14,fontWeight:500,color:h},children:y>0?`${y}d`:y===0?"TODAY":`${Math.abs(y)}d OVERDUE`})," "]})," ",e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,fontSize:14,color:"#71717A"},children:[" ",e.jsxs("span",{children:["Due: ",Z(l.dueDate)]}),l.extendedDueDate&&e.jsxs("span",{children:["Extended: ",Z(l.extendedDueDate)]}),l.amountDue&&e.jsxs("span",{children:["Amount:"," ",e.jsx("span",{className:"u-nums",style:{color:"#27272A"},children:A(l.amountDue)})]})," ",e.jsx(O,{label:"Filing status",className:"min-w-0",children:e.jsx(ae,{value:l.status,onChange:T=>B(l.id,T.target.value),style:{minWidth:100},disabled:!!i,children:Un.map(T=>e.jsx("option",{value:T,children:T.charAt(0).toUpperCase()+T.slice(1)},T))})})," "]})," "]},l.id)}),p.length>0&&e.jsxs("div",{style:{marginTop:20},children:[" ",e.jsxs("div",{style:{fontSize:14,color:"#71717A",marginBottom:8},children:["Completed (",p.length,")"]}),p.map(l=>e.jsxs(M,{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",marginBottom:3,opacity:.7},children:[" ",e.jsx(te,{tone:"neutral",children:l.status})," ",e.jsx("span",{style:{fontSize:14,color:"#27272A",flex:1},children:l.title})," ",e.jsxs("span",{style:{fontSize:14,color:"#71717A"},children:["Due: ",Z(l.dueDate)]}),l.filedDate&&e.jsxs("span",{style:{fontSize:14,color:"#18181B"},children:["Filed: ",Z(l.filedDate)]}),l.amountPaid&&e.jsx("span",{className:"u-nums",style:{fontSize:14,color:"#18181B"},children:A(l.amountPaid)})]},l.id))]})]})}function Xn(){var _,H,G,J;const a=s.useRef(!1),[i,r]=s.useState(""),[S,o]=s.useState(""),[f,x]=s.useState([]),[$,m]=s.useState([]),[B,N]=s.useState({}),[p,l]=s.useState(null),[y,h]=s.useState(!1),[T,v]=s.useState("new"),g=me("/admin/tax/advisor/reports",x,"reports"),d=s.useCallback(c=>{m(c.alerts||[]),N(c.counts||{})},[]),n=me(`/admin/tax/advisor/alerts?status=${T}`,d);s.useEffect(()=>{l(c=>c||f[0]||null)},[f]);const b=async()=>{var c;if(!a.current){a.current=!0,r("handleRunAdvisor"),o("");try{h(!0);try{await F("/admin/tax/advisor/run",{method:"POST"});const q=await F("/admin/tax/advisor/reports");x(q.reports||[]),(c=q.reports)!=null&&c.length&&l(q.reports[0]);const R=await F("/admin/tax/advisor/alerts?status=new");m(R.alerts||[]),N(R.counts||{})}catch(q){o("Failed: "+q.message)}h(!1)}finally{a.current=!1,r("")}}},P=async(c,q)=>{if(!a.current){a.current=!0,r("handleAlertAction"),o("");try{try{await F(`/admin/tax/advisor/alerts/${c}`,{method:"PUT",body:JSON.stringify({status:q})});const R=await F(`/admin/tax/advisor/alerts?status=${T}`);m(R.alerts||[]),N(R.counts||{})}catch(R){o(R.message)}}finally{a.current=!1,r("")}}},z=p,Q={A:"#18181B",B:"#18181B",C:"#52525B",D:"#18181B",F:"#C8312F"}[z==null?void 0:z.grade]||"#71717A";return e.jsxs("div",{children:[(g.loading||g.error)&&e.jsx(ve,{read:g,label:"advisor reports"}),(n.loading||n.error)&&e.jsx(ve,{read:n,label:"advisor alerts"}),S&&e.jsx(K,{error:!0,className:"mb-4 whitespace-pre-wrap",children:S})," ",e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16},children:[" ",e.jsxs("div",{children:[" ",e.jsx("h2",{style:{fontSize:18,fontWeight:500,color:"#09090B"},children:"AI Tax Advisor"})," ",e.jsx("div",{style:{fontSize:14,color:"#71717A"},children:"Weekly analysis of tax situation, regulations & savings"})," "]})," ",e.jsx(E,{onClick:b,disabled:!!i||y,type:"button",variant:"secondary",className:"min-w-11",loading:i==="handleRunAdvisor",children:"Run Advisor Now"})," "]}),(B.new||0)>0&&e.jsxs("div",{style:{marginBottom:20},children:[" ",e.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",marginBottom:10},children:[" ",e.jsx("div",{style:{fontSize:14,fontWeight:500,color:"#09090B"},children:"Action Items"}),["new","reviewed","acted_on","dismissed"].map(c=>e.jsxs(E,{onClick:()=>{v(c)},type:"button",variant:T===c?"primary":"secondary","aria-pressed":T===c,className:"min-w-11",disabled:!!i,children:[c.replace("_"," ")," ",B[c]?`(${B[c]})`:""]},c))]}),$.map(c=>e.jsxs(M,{style:{padding:"10px 14px",marginBottom:4},children:[" ",e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[" ",e.jsx(te,{tone:Ue[c.priority]==="#C8312F"?"alert":"neutral",children:c.priority})," ",e.jsx(te,{tone:"neutral",children:c.type})," ",e.jsx("span",{style:{fontSize:14,fontWeight:500,color:"#09090B",flex:1},children:c.title}),c.estimatedSavings&&e.jsxs("span",{className:"u-nums",style:{fontSize:14,fontWeight:500,color:"#18181B"},children:["~",A(c.estimatedSavings),"/yr"]})]}),c.description&&e.jsx("div",{style:{fontSize:14,color:"#71717A",marginBottom:6},children:c.description}),e.jsxs("div",{style:{display:"flex",gap:4},children:[c.status==="new"&&e.jsx(E,{onClick:()=>P(c.id,"reviewed"),type:"button",variant:"primary",className:"min-w-11",disabled:!!i,children:"Mark Reviewed"}),(c.status==="new"||c.status==="reviewed")&&e.jsx(E,{onClick:()=>P(c.id,"acted_on"),type:"button",variant:"primary",className:"min-w-11",disabled:!!i,children:"Done"}
1),c.status!=="dismissed"&&e.jsx(E,{onClick:()=>P(c.id,"dismissed"),type:"button",variant:"secondary",className:"min-w-11",disabled:!!i,children:"Dismiss"})]})," "]},c.id))]}),f.length>0&&e.jsx("div",{style:{display:"flex",gap:6,marginBottom:14,flexWrap:"wrap"},children:f.slice(0,8).map(c=>e.jsxs(E,{onClick:()=>l(c),type:"button",variant:(p==null?void 0:p.id)===c.id?"primary":"secondary","aria-pressed":(p==null?void 0:p.id)===c.id,className:"min-w-11",disabled:!!i,children:[c.period||Z(c.date)," ",e.jsx("span",{style:{fontWeight:500,color:{A:"#18181B",B:"#18181B",C:"#52525B"}[c.grade]||"#71717A"},children:c.grade})," "]},c.id))}),z?e.jsxs("div",{children:[" ",e.jsxs(M,{style:{padding:"16px 20px",marginBottom:12},children:[" ",e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:10},children:[" ",e.jsx("span",{className:"u-nums",style:{fontSize:32,fontWeight:500,color:Q},children:z.grade})," ",e.jsxs("div",{children:[" ",e.jsx("div",{style:{fontSize:14,fontWeight:500,color:"#09090B"},children:z.period})," ",e.jsx("div",{style:{fontSize:14,color:"#71717A"},children:z.date})," "]})," "]})," ",e.jsx("div",{style:{fontSize:14,color:"#27272A",lineHeight:1.6},children:z.summary})," "]}),((_=z.regulationChanges)==null?void 0:_.length)>0&&e.jsxs("div",{style:{marginBottom:14},children:[" ",e.jsx("div",{style:{fontSize:14,fontWeight:500,color:"#09090B",marginBottom:8},children:"Regulation Changes Found"}),z.regulationChanges.map((c,q)=>e.jsxs(M,{style:{padding:"10px 14px",marginBottom:4},children:[" ",e.jsx("div",{style:{fontSize:14,fontWeight:500,color:"#09090B",marginBottom:4},children:c.change})," ",e.jsx("div",{style:{fontSize:14,color:"#71717A"},children:c.impact}),c.action_required&&e.jsxs("div",{style:{fontSize:14,color:"#52525B",marginTop:4},children:["Action: ",c.action_required]}),e.jsxs("div",{style:{fontSize:14,color:"#71717A",marginTop:4},children:[c.source," ",c.effective_date&&`· Effective ${c.effective_date}`]})," "]},q))]}),((H=z.savingsOpportunities)==null?void 0:H.length)>0&&e.jsxs("div",{style:{marginBottom:14},children:[" ",e.jsx("div",{style:{fontSize:14,fontWeight:500,color:"#09090B",marginBottom:8},children:"Savings Opportunities"}),z.savingsOpportunities.map((c,q)=>e.jsxs(M,{style:{padding:"10px 14px",marginBottom:4},children:[" ",e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[" ",e.jsx(te,{tone:Ue[c.priority]==="#C8312F"?"alert":"neutral",children:c.priority})," ",e.jsx("span",{style:{fontSize:14,fontWeight:500,color:"#09090B",flex:1},children:c.title}),c.estimated_annual_savings&&e.jsxs("span",{className:"u-nums",style:{fontSize:14,fontWeight:500,color:"#18181B"},children:["~",A(c.estimated_annual_savings),"/yr"]})]})," ",e.jsx("div",{style:{fontSize:14,color:"#71717A",marginTop:4},children:c.action})," "]},q))]}),((G=z.deductionGaps)==null?void 0:G.length)>0&&e.jsxs("div",{style:{marginBottom:14},children:[" ",e.jsx("div",{style:{fontSize:14,fontWeight:500,color:"#09090B",marginBottom:8},children:"Deduction Gaps"}),z.deductionGaps.map((c,q)=>e.jsxs(M,{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",marginBottom:3},children:[" ",e.jsx("span",{style:{fontSize:14,color:"#09090B",flex:1},children:c.deduction}),c.estimated_value&&e.jsx("span",{className:"u-nums",style:{fontSize:14,color:"#18181B"},children:A(c.estimated_value)}),c.irs_reference&&e.jsx("span",{style:{fontSize:14,color:"#71717A"},children:c.irs_reference})]},q))]}),((J=z.complianceAlerts)==null?void 0:J.length)>0&&e.jsxs("div",{children:[" ",e.jsx("div",{style:{fontSize:14,fontWeight:500,color:"#09090B",marginBottom:8},children:"Compliance Alerts"}),z.complianceAlerts.map((c,q)=>e.jsxs(M,{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",marginBottom:3},children:[" ",e.jsx(te,{tone:Ue[c.severity]==="#C8312F"?"alert":"neutral",children:c.severity})," ",e.jsx("span",{style:{fontSize:14,color:"#09090B",flex:1},children:c.alert}),c.deadline&&e.jsxs("span",{style:{fontSize:14,color:"#52525B"},children:["By: ",c.deadline]})]},q))]})]}):e.jsxs("div",{style:{padding:40,textAlign:"center"},children:[" ",e.jsx("div",{style:{fontSize:48,marginBottom:12},children:"AI"})," ",e.jsx("div",{style:{fontSize:15,fontWeight:500,color:"#09090B",marginBottom:6},children:"No Advisor Reports Yet"})," ",e.jsx("div",{style:{fontSize:14,color:"#71717A",maxWidth:400,margin:"0 auto"},children:'Click "Run Advisor Now" to generate your first weekly tax analysis. The advisor will search for current regulations, analyze your financials, and identify savings opportunities.'})," "]})]})}function Zn(){const[a,i]=s.useState([]),r=me("/admin/tax/exemptions",i,"exemptions");return r.loading||r.error?e.jsx(ve,{read:r,label:"exemptions"}):e.jsxs("div",{children:[" ",e.jsx("h2",{style:{fontSize:18,fontWeight:500,color:"#09090B",marginBottom:4},children:"Tax Exemption Certificates"})," ",e.jsx("div",{style:{fontSize:14,color:"#71717A",marginBottom:14},children:"DR-14 exemption certificates for tax-exempt customers"}),a.length===0?e.jsx("div",{style:{padding:30,textAlign:"center",color:"#71717A",fontSize:14},children:"No exemption certificates on file. Add one when a customer provides a DR-14."}):a.map(S=>e.jsxs(M,{style:{padding:"10px 14px",marginBottom:4},children:[" ",e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[" ",e.jsx("span",{style:{fontSize:14,fontWeight:500,color:"#09090B",flex:1},children:S.customerName})," ",e.jsx(te,{tone:"neutral",children:S.verified?"Verified":"Unverified"})," ",e.jsx(te,{tone:"neutral",children:S.exemptionType})," "]})," ",e.jsxs("div",{style:{display:"flex",gap:12,fontSize:14,color:"#71717A",marginTop:4},children:[" ",e.jsxs("span",{children:["Cert: ",S.certificateNumber||"—"]})," ",e.jsxs("span",{children:["Expires: ",Z(S.expiryDate)]})," "]})," "]},S.id))]})}function Qn(){const a=s.useRef(!1),[i,r]=s.useState(""),[S,o]=s.useState(""),f=be(640),x=s.useRef(0),[$,m]=s.useState(""),[B,N]=s.useState([]),[p,l]=s.useState(null),[y,h]=s.useState(null),[T,v]=s.useState(!0),[g,d]=s.useState(!1),[n,b]=s.useState("all"),[P,z]=s.useState(()=>new Set),[Q,_]=s.useState(!1),[H,G]=s.useState({trip_date:je(),start_address:"",end_address:"",distance_miles:"",purpose:"business",notes:""}),J=(j=n)=>{const I=++x.current;v(!0),m("");const u=j==="all"?"/admin/tax/mileage?limit=200":`/admin/tax/mileage?limit=200&purpose=${j}`;Promise.all([F(u).catch(C=>({entries:[],error:C.message})),F("/admin/tax/mileage/stats").catch(C=>({error:(C==null?void 0:C.message)||"Failed to load"}))]).then(([C,k])=>{I===x.current&&(m((C==null?void 0:C.error)||""),N(C&&(C.entries||C)||[]),k&&k.error?(l(null),h(k.error)):(l(k),h(null)),z(new Set),v(!1))})};s.useEffect(()=>J(n),[n]);const c=async j=>{if(!a.current){a.current=!0,r("bulkClassify"),o("");try{const I=[...P];if(!I.length||!window.confirm(`Mark ${I.length} trip${I.length===1?"":"s"} as ${j.toUpperCase()}?${j==="business"?" Their deduction recomputes at that year's IRS rate.":" Their deduction becomes $0."}`))return;_(!0);try{const u=await F("/admin/tax/mileage/bulk-classify",{method:"POST",body:JSON.stringify({ids:I,purpose:j})});let C=`${u.updated} trip${u.updated===1?"":"s"} marked ${j}${j==="business"?` — ${A(u.deductionTotal)} in deductions`:""}`;u.skippedNoRate&&(C+=`
2
3⚠ ${u.skippedNoRate} trip${u.skippedNoRate===1?"":"s"} left UNCLASSIFIED — no verified IRS rate for their date yet. Add the published rate, then reclassify.`),u.summaryRecomputeFailures&&(C+=`
4
5⚠ Mileage summaries for ${u.summaryRecomputeFailures} day/month bucket${u.summaryRecomputeFailures===1?"":"s"} could not be recomputed — dashboards may be briefly stale (the classification itself is saved). Re-run Sync to repair.`),alert(C),J(
5)}catch(u){o(`Classification failed: ${u.message}`)}_(!1)}finally{a.current=!1,r("")}}},q=async()=>{var j;if(!a.current){a.current=!0,r("handleSync"),o("");try{d(!0);try{const I=await F("/admin/tax/mileage/sync-bouncie",{method:"POST"});alert(`Bouncie sync: ${I.tripsImported||0} trips imported, ${((j=I.totalMiles)==null?void 0:j.toFixed(1))||0} miles, ${A(I.deductionAmount)} deduction`),J()}catch(I){o(`Sync failed: ${I.message}`)}d(!1)}finally{a.current=!1,r("")}}},R=async()=>{if(!a.current){a.current=!0,r("handleAdd"),o("");try{if(!H.distance_miles)return;try{await F("/admin/tax/mileage",{method:"POST",body:JSON.stringify(H)}),G(j=>({...j,start_address:"",end_address:"",distance_miles:"",notes:""})),J()}catch(j){o(`Failed: ${j.message}`)}}finally{a.current=!1,r("")}}};return T?e.jsx("div",{style:{color:"#71717A",padding:40,textAlign:"center"},children:"Loading mileage..."}):e.jsxs("div",{children:[$&&e.jsxs(K,{error:!0,onRetry:()=>J(),children:["Could not load mileage entries: ",$]}),S&&e.jsx(K,{error:!0,className:"mb-4 whitespace-pre-wrap",children:S}),y&&e.jsxs("div",{style:{background:"#C8312F11",border:"1px solid #C8312F",borderRadius:8,padding:"12px 16px",marginBottom:16,color:"#C8312F",fontSize:14},children:["Couldn't load mileage totals (",y,") — YTD figures are unknown, not zero."]}),p&&e.jsxs("div",{style:{display:"flex",gap:10,marginBottom:16,flexWrap:"wrap"},children:[" ",e.jsx(Y,{label:"YTD Miles Logged",value:`${(p.totalMiles||0).toLocaleString()} mi`,color:"#18181B"})," ",e.jsx(Y,{label:"YTD Deduction",value:A(p.totalDeduction),color:"#18181B",sub:p.irsRate!=null?`@ $${p.irsRate}/mile`:void 0})," ",e.jsx(Y,{label:"Total Trips",value:p.totalTrips||0,color:"#18181B"})," ",e.jsx(Y,{label:"Avg Trip",value:`${(p.avgDistance||0).toFixed(1)} mi`,color:"#71717A"})," "]}),e.jsxs("div",{style:{display:"flex",gap:8,marginBottom:12,flexWrap:"wrap",alignItems:"center"},children:[e.jsx(O,{label:"Show:",className:"min-w-0",children:e.jsxs(ae,{value:n,onChange:j=>b(j.target.value),disabled:!!i,children:[e.jsx("option",{value:"all",children:"All trips"}),e.jsx("option",{value:"unclassified",children:"Unclassified"}),e.jsx("option",{value:"business",children:"Business"}),e.jsx("option",{value:"personal",children:"Personal"})]})}),P.size>0&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{style:{fontSize:14,color:"#71717A"},children:[P.size," selected"]}),e.jsx(E,{onClick:()=>c("business"),disabled:!!i||Q,type:"button",variant:"primary",className:"min-w-11",children:"Mark business"}),e.jsx(E,{onClick:()=>c("personal"),disabled:!!i||Q,type:"button",variant:"secondary",className:"min-w-11",children:"Mark personal"})]})]}),e.jsxs("div",{style:{display:"flex",gap:8,marginBottom:16,flexWrap:"wrap",alignItems:"flex-end"},children:[" ",e.jsx(E,{onClick:q,disabled:!!i||g,type:"button",variant:"primary",className:"min-w-11",loading:i==="handleSync",children:" Sync from Bouncie"})," ",e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:10,alignItems:"flex-end"},children:[" ",e.jsx("div",{children:e.jsx(O,{label:"Date",className:"min-w-0",children:e.jsx(X,{type:"date",value:H.trip_date,onChange:j=>G(I=>({...I,trip_date:j.target.value})),style:{width:130},disabled:!!i})})})," ",e.jsx("div",{children:e.jsx(O,{label:"From",className:"min-w-0",children:e.jsx(X,{value:H.start_address,onChange:j=>G(I=>({...I,start_address:j.target.value})),placeholder:"Start",style:{width:140},disabled:!!i})})})," ",e.jsx("div",{children:e.jsx(O,{label:"To",className:"min-w-0",children:e.jsx(X,{value:H.end_address,onChange:j=>G(I=>({...I,end_address:j.target.value})),placeholder:"End",style:{width:140},disabled:!!i})})})," ",e.jsx("div",{children:e.jsx(O,{label:"Miles",className:"min-w-0",children:e.jsx(X,{type:"number",value:H.distance_miles,onChange:j=>G(I=>({...I,distance_miles:j.target.value})),placeholder:"0.0",step:"0.1",style:{width:70},disabled:!!i})})})," ",e.jsx(O,{label:"Trip purpose",className:"min-w-0",children:e.jsxs(ae,{value:H.purpose,onChange:j=>G(I=>({...I,purpose:j.target.value})),disabled:!!i,children:[e.jsx("option",{value:"business",children:"Business"}),e.jsx("option",{value:"personal",children:"Personal"}),e.jsx("option",{value:"commute",children:"Commute"})]})})," ",e.jsx(E,{onClick:R,type:"button",variant:"primary",className:"min-w-11",disabled:!!i,loading:i==="handleAdd",children:"+ Add"})," "]})," "]}),B.length===0?e.jsx(M,{style:{padding:40,textAlign:"center",color:"#71717A"}
5,children:"No mileage entries yet. Sync from Bouncie or add manually."}):e.jsxs(M,{style:{overflow:"hidden",overflowX:"auto",WebkitOverflowScrolling:"touch"},children:[" ",e.jsxs(Pe,{style:{minWidth:f?600:void 0},children:[e.jsx(Fe,{children:e.jsxs(fe,{children:[e.jsx(ye,{children:e.jsx("label",{className:"ui-choice-label justify-center",children:e.jsx($e,{type:"checkbox",checked:B.length>0&&P.size===B.length,onChange:j=>z(j.target.checked?new Set(B.map(I=>I.id)):new Set),"aria-label":"Select all listed trips",disabled:!!i})})}),["Date","From","To","Miles","Purpose","Deduction","Source"].map(j=>e.jsx(ye,{style:{color:"#71717A",textAlign:"left"},children:j},j))]})}),e.jsx(Le,{children:B.map((j,I)=>e.jsxs(fe,{style:{borderBottom:"1px solid #E4E4E722"},children:[e.jsx(V,{children:e.jsx("label",{className:"ui-choice-label justify-center",children:e.jsx($e,{type:"checkbox",checked:P.has(j.id),onChange:u=>z(C=>{const k=new Set(C);return u.target.checked?k.add(j.id):k.delete(j.id),k}),"aria-label":"Select trip",disabled:!!i})})}),e.jsx(V,{children:Z(j.tripDate||j.trip_date)}),e.jsx(V,{style:{color:"#71717A",maxWidth:150,overflow:"hidden",textOverflow:"ellipsis"},children:j.startAddress||j.start_address||"—"}),e.jsx(V,{style:{color:"#71717A",maxWidth:150,overflow:"hidden",textOverflow:"ellipsis"},children:j.endAddress||j.end_address||"—"}),e.jsx(V,{style:{color:"#09090B"},children:parseFloat(j.distanceMiles??j.distance_miles??0).toFixed(1)}),e.jsx(V,{children:e.jsx(te,{tone:"neutral",children:j.purpose})}),e.jsx(V,{style:{color:"#18181B"},children:A(j.deductionAmount??j.deduction_amount)}),e.jsx(V,{children:e.jsx(te,{tone:"neutral",children:j.source||"manual"})})]},j.id||I))})]})," "]})]})}function es(){const a=s.useRef(0),i=be(640),[r,S]=s.useState(()=>{const p=new Date;return`${p.getFullYear()}-${String(p.getMonth()+1).padStart(2,"0")}`}),[o,f]=s.useState(null),[x,$]=s.useState(null),[m,B]=s.useState(!0),N=()=>{const p=++a.current;B(!0);const[l,y]=String(r).split("-"),h=parseInt(y,10)||1,T=`Q${Math.ceil(h/3)}`;Promise.all([F(`/admin/tax/revenue/reconcile?month=${r}`).catch(()=>null),F(`/admin/tax/revenue/quarterly-estimate?quarter=${T}&year=${l}`).catch(()=>null)]).then(([v,g])=>{p===a.current&&(f(v),$(g),B(!1))})};return s.useEffect(N,[r]),m?e.jsx("div",{style:{color:"#71717A",padding:40,textAlign:"center"},children:"Loading revenue data..."}):e.jsxs("div",{children:[!o&&e.jsx(K,{error:!0,onRetry:N,children:"Could not load revenue reconciliation."}),!x&&e.jsx(K,{error:!0,onRetry:N,children:"Could not load the quarterly estimate."}),e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:16},children:[" ",e.jsx(O,{label:"Month:",className:"min-w-0",children:e.jsx(X,{type:"month",value:r,onChange:p=>S(p.target.value),style:{width:160}})})," "]}),o&&e.jsxs("div",{style:{display:"flex",gap:10,marginBottom:16,flexWrap:"wrap"},children:[" ",e.jsx(Y,{label:"Revenue",value:A(o.totalRevenue),color:"#18181B"})," ",e.jsx(Y,{label:"Tax Collected",value:A(o.taxCollected),color:"#52525B"})," ",e.jsx(Y,{label:"Tax Owed",value:A(o.taxOwed),color:"#18181B"})," ",e.jsx(Y,{label:"Difference",value:o.taxCollected!=null&&o.taxOwed!=null?A(o.taxCollected-o.taxOwed):"—",color:o.taxCollected!=null&&o.taxOwed!=null?o.taxCollected>=o.taxOwed?"#18181B":"#C8312F":"#71717A",sub:o.taxCollected!=null&&o.taxOwed!=null?o.taxCollected>=o.taxOwed?"Over-collected":"Under-collected":"Not recorded"})," "]}),(o==null?void 0:o.note)&&e.jsx("div",{style:{fontSize:14,color:"#71717A",marginTop:-6,marginBottom:16},children:o.note}),x&&e.jsxs(M,{style:{padding:20,marginBottom:16},children:[" ",e.jsxs("div",{style:{fontSize:14,fontWeight:500,color:"#09090B",marginBottom:12},children:["Quarterly Estimated Tax Payment — ",x.quarter]})," ",e.jsx("div",{style:{display:"grid",gridTemplateColumns:i?"1fr":"1fr 1fr",gap:8,fontSize:14},children:[["YTD Revenue (excl. sales tax)",A(x.ytdRevenue)],["YTD Deductible Expenses",A(x.ytdExpenses)],["YTD Net Income",A(x.estimatedNetIncome)],["Annualized Net Income",A(x.annualizedNet)],["Self-Employment Tax (15.3%, annual)",A(x.seTax)],["Estimated Income Tax (22%, annual)",A(x.incomeTax)],["Required Cumulative Through Quarter",A(x.requiredCumulative)],["Prior 1040-ES Payments Credited",A(x.priorPaymentsCredited)],["Total Quarterly Payment",A(x.quarterlyPayment)]].map(([p,l])=>e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"4px 0",borderBottom:"1px solid #E4E4E722"},children:[" ",e.jsx("span",{style:{color:"#71717A"},children:p})," ",e.jsx("span",{className:"u-nums",style:{color:"#09090B"},children:l})," "]},p))}),x.dueDate&&e.jsxs("div",{style:{marginTop:12,fontSize:14,color:"#52525B"},children:["Due: ",Z(x.dueDate)]}),x.note&&e.jsx("div",{style:{marginTop:8,fontSize:14,color:"#71717A"},children:x.note})]}),!o&&!x&&e.jsx(M,{style:{padding:40,textAlign:"center",color:"#71717A"},children:"No revenue data available for this period."})]})}function ts(){var H,G,J,c,q,R,j,I,u,C,k,ne,he,Re,De,Ie,Ce;const a=s.useRef(!1),[i,r]=s.useState(""),[S,o]=s.useState(""),f=s.useRef(0),[x,$]=s.useState(""),[m,B]=s.useState(null),[N,p]=s.useState(!0),[l,y]=s.useState("mtd"),[h,T]=s.useState(""),[v,g]=s.useState(""),[d,n]=s.useState(!1),b=s.useCallback(async()=>{const U=++f.current;$(""),p(!0);
5try{let ee=`/admin/tax/pnl?period=${l}`;l==="custom"&&h&&v&&(ee+=`&start_date=${h}&end_date=${v}`);const re=await F(ee);if(U!==f.current)return;B(re)}catch(ee){U===f.current&&(B(null),$(ee.message))}U===f.current&&p(!1)},[l,h,v]);s.useEffect(()=>{b()},[b]);const P=async U=>{if(!a.current){a.current=!0,r("setVehicleMethod"),o("");try{const ee=U===""?null:U,re={standard_mileage:"Standard mileage",actual_expenses:"Actual vehicle expenses",null:"Not elected"};if(!window.confirm(`Record your intended vehicle deduction method as "${re[ee]}"? This P&L always reports ACTUAL vehicle costs — the setting doesn't change the totals; if you choose standard mileage it just discloses the mileage figure to apply manually with your CPA (line 9 allows one method, not both).`))return;n(!0);try{await F("/admin/revenue/settings",{method:"PUT",body:JSON.stringify({vehicleDeductionMethod:ee})}),await b()}catch(se){o(`Could not save election: ${se.message||se}`)}n(!1)}finally{a.current=!1,r("")}}},z=async()=>{if(!a.current){a.current=!0,r("downloadPnl"),o("");try{try{let U=`${Ye}/admin/tax/export/pnl?period=${l}`;l==="custom"&&h&&v&&(U+=`&start_date=${h}&end_date=${v}`);const ee=await fetch(U,{headers:{Authorization:`Bearer ${localStorage.getItem("waves_admin_token")}`}});if(!ee.ok)throw new Error(`HTTP ${ee.status}`);const re=await ee.blob(),se=document.createElement("a");se.href=URL.createObjectURL(re),se.download=`waves-pnl-${l}-${je()}.csv`,se.click()}catch(U){o("Download failed: "+U.message)}}finally{a.current=!1,r("")}}},Q=[{id:"mtd",label:"This Month"},{id:"last_month",label:"Last Month"},{id:"quarterly",label:"This Quarter"},{id:"ytd",label:"YTD"},{id:"last_year",label:"Last Year"},{id:"custom",label:"Custom"}],_=({label:U,value:ee,bold:re,indent:se,color:ke})=>e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:`${re?6:4}px 0`,borderBottom:re?"1px solid #E4E4E7":"1px solid #E4E4E722",marginLeft:se?20:0},children:[" ",e.jsx("span",{style:{fontSize:14,color:re?"#09090B":"#71717A",fontWeight:re?700:400},children:U})," ",e.jsx("span",{className:"u-nums",style:{fontSize:14,fontWeight:re?700:400,color:ke||(re?"#09090B":"#27272A"),textAlign:"right"},children:A(ee)})," "]});return e.jsxs("div",{children:[x&&e.jsxs(K,{error:!0,onRetry:b,children:["Could not load P&L: ",x]}),S&&e.jsx(K,{error:!0,className:"mb-4 whitespace-pre-wrap",children:S})," ",e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:14},children:[" ",e.jsxs("div",{children:[" ",e.jsx("h2",{style:{fontSize:18,fontWeight:500,color:"#09090B"},children:"Profit & Loss Statement"})," ",e.jsx("div",{style:{fontSize:14,color:"#71717A"},children:m?`${m.startDate} to ${m.endDate}`:"Select a period"}),((H=m==null?void 0:m.coverage)==null?void 0:H.note)&&e.jsx("div",{style:{fontSize:14,color:"#52525B",marginTop:4,maxWidth:620},children:m.coverage.note})," "]})," ",e.jsx(E,{onClick:z,type:"button",variant:"primary",className:"min-w-11",disabled:!!i,loading:i==="downloadPnl",children:"Download P&L"})," "]}),e.jsxs("div",{style:{display:"flex",gap:4,marginBottom:14,flexWrap:"wrap",alignItems:"center"},children:[Q.map(U=>e.jsx(E,{onClick:()=>y(U.id),type:"button",variant:l===U.id?"primary":"secondary","aria-pressed":l===U.id,className:"min-w-11",disabled:!!i,children:U.label},U.id)),l==="custom"&&e.jsxs(e.Fragment,{children:[" ",e.jsx(O,{label:"Start date",className:"min-w-0",children:e.jsx(X,{type:"date",value:h,onChange:U=>T(U.target.value),style:{width:130},disabled:!!i})})," ",e.jsx("span",{style:{color:"#71717A",fontSize:14},children:"to"})," ",e.jsx(O,{label:"End date",className:"min-w-0",children:e.jsx(X,{type:"date",value:v,onChange:U=>g(U.target.value),style:{width:130},disabled:!!i})})," "]})]}),N?e.jsx("div",{style:{padding:40,textAlign:"center",color:"#71717A"},children:"Loading P&L..."}):m?e.jsxs(M,{style:{padding:"20px 24px"},children:[" ",e.jsx(_,{label:"REVENUE",value:null,bold:!0})," ",e.jsx(_,{label:"Service Revenue",value:(G=m.revenue)==null?void 0:G.serviceRevenue,indent:!0})," ",e.jsx(_,{label:"Other Revenue",value:(J=m.revenue)==null?void 0:J.otherRevenue,indent:!0})," ",e.jsx(_,{label:"Total Revenue",value:(c=m.revenue)==null?void 0:c.total,bold:!0})," ",e.jsx(_,{label:"Sales tax collected (liability, not income)",value:(q=m.revenue)==null?void 0:q.salesTaxCollected,indent:!0})," ",e.jsx("div",{style:{height:12}})," ",e.jsx(_,{label:"COST OF GOODS SOLD",value:null,bold:!0})," ",e.jsx(_,{label:"Labor",value:(R=m.cogs)==null?void 0:R.labor,indent:!0})," ",e.jsx(_,{label:"Materials & Supplies",value:(j=m.cogs)==null?void 0:j.materials,indent:!0})," ",e.jsx(_,{label:"Total COGS",value:(I=m.cogs)==null?void 0:I.total,bold:!0})," ",e.jsx("div",{style:{height:12}})," ",e.jsx(_,{label:"GROSS PROFIT",value:m.grossProfit,bold:!0,color:m.grossProfit>=0?"#18181B":"#C8312F"})," ",e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"4px 0",borderBottom:"1px solid #E4E4E722"},children:[" ",e.jsx("span",{style:{fontSize:14,color:"#71717A"},children:"Gross Margin"})," ",e.jsxs("span",{className:"u-nums",style:{fontSize:14,color:"#27272A"},children:[((m.grossMargin||0)*100).toFixed(1),"%"]})," "]})," ",e.jsx("div",{style:{height:12}})," ",e.jsx(_,{label:"OPERATING EXPENSES",value:null,bold:!0}),(C=(u=m.operatingExpenses)==null?void 0:u.categories)==null?void 0:C.map((U,ee)=>e.jsx(_,{label:U.name,value:U.amount,indent:!0},ee)),e.jsx(_,{label:"Total Operating Expenses",value:(k=m.operatingExpenses)==null?void 0:k.total,bold:!0})," ",e.jsx("div",{style:{height:12}})," ",e.jsx(_,{label:"DEDUCTIONS",value:null,bold:!0})," ",e.jsx(_,{label:"Mileage Deduction",value:(ne=m.deductions)==null?void 0:ne.mileage,indent:!0})," ",e.jsx(_,{label:((he=m.deductions)==null?void 0:he.depreciationComplete)===!1?"Depreciation (incomplete)":"Depreciation",value:(Re=m.deductions)==null?void 0:Re.depreciation,indent:!0})," ",e.jsx(_,{label:"Total Deductions",value:(De=m.deductions)==null?void 0:De.total,bold:!0})," ",((Ie=m.depreciationDisclosure)==null?void 0:Ie.note)&&e.jsx("div",{style:{marginTop:6,padding:"8px 10px",border:"1px solid #52525B",borderRadius:6,color:"#52525B",fontSize:14,lineHeight:1.45},children:m.depreciationDisclosure.note})," ",m.vehicleDeduction&&e.jsx("div",{style:{marginTop:8,display:"flex",alignItems:"center",gap:8,fontSize:14,color:"#71717A"},children:e.jsx(O,{label:"Intended vehicle method (informational \\u2014 P&L reports actual costs):",className:"min-w-0",children:e.jsxs(ae,{value:m.vehicleDeduction.method||"",disabled:!!i||d,onChange:U=>P(U.target.value),style:{minWidth:180},children:[e.jsx("option",{value:"",children:"Not elected"}),e.jsx("option",{value:"standard_mileage",children:"Standard mileage"}),e.jsx("option",{value:"actual_expenses",children:"Actual vehicle expenses"})]})})})," ",m.vehicleDeduction&&m.vehicleDeduction.standardMileageComputed>0&&!m.vehicleDeduction.methodConflict&&e.jsxs("div",{style:{marginTop:6,padding:"8px 10px",border:"1px solid #52525B",borderRadius:6,color:"#52525B",fontSize:14,lineHeight:1.45},children:["This P&L deducts actual vehicle costs. Standard mileage for the peri
5od would be"," ",A(m.vehicleDeduction.standardMileageComputed)," — it is not added here (Schedule C line 9 allows actual expenses OR mileage, not both). Apply it with your CPA in place of the actual vehicle costs only if you use the standard method."]})," ",((Ce=m.vehicleDeduction)==null?void 0:Ce.methodConflict)&&e.jsx("div",{style:{marginTop:6,padding:"8px 10px",border:"1px solid #C8312F",borderRadius:6,color:"#C8312F",fontSize:14,lineHeight:1.45},children:m.vehicleDeduction.methodConflict.note})," ",e.jsx("div",{style:{height:16}})," ",e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"10px 0",borderTop:"2px solid #E4E4E7"},children:[" ",e.jsx("span",{style:{fontSize:16,fontWeight:500,color:"#09090B"},children:"NET INCOME"})," ",e.jsx("span",{className:"u-nums",style:{fontSize:18,fontWeight:500,color:m.netIncome>=0?"#18181B":"#C8312F"},children:A(m.netIncome)})," "]})," ",e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"4px 0"},children:[" ",e.jsx("span",{style:{fontSize:14,color:"#71717A"},children:"Net Margin"})," ",e.jsxs("span",{className:"u-nums",style:{fontSize:14,color:m.netIncome>=0?"#18181B":"#C8312F"},children:[((m.netMargin||0)*100).toFixed(1),"%"]})," "]})," "]}):e.jsx("div",{style:{padding:40,textAlign:"center",color:"#71717A"},children:"No financial data available for this period."})]})}function ns(){const a=s.useRef(!1),[i,r]=s.useState(""),[S,o]=s.useState(""),f=be(640),[x,$]=s.useState(String(new Date().getFullYear())),[m,B]=s.useState(`${new Date().getFullYear()}-01-01`),[N,p]=s.useState(je()),[l,y]=s.useState(""),h=async(v,g)=>{if(!a.current){a.current=!0,r("download"),o("");try{y(v);try{let d=`${Ye}/admin/tax/export/${v}`;v==="tax-package"?d+=`?year=${x}`:v!=="depreciation"&&(d+=`?start_date=${m}&end_date=${N}`);const n=await fetch(d,{headers:{Authorization:`Bearer ${localStorage.getItem("waves_admin_token")}`}});if(!n.ok)throw new Error(`HTTP ${n.status}`);const b=await n.blob(),P=document.createElement("a");P.href=URL.createObjectURL(b),P.download=g,P.click(),URL.revokeObjectURL(P.href)}catch(d){o("Download failed: "+d.message)}y("")}finally{a.current=!1,r("")}}},T=[{type:"transactions",label:"Transactions",desc:"All payment transactions",icon:"$",color:"#18181B"},{type:"expenses",label:"Expenses",desc:"Schedule C categories",icon:"E",color:"#52525B"},{type:"mileage",label:"Mileage",desc:"IRS mileage log",icon:"M",color:"#18181B"},{type:"depreciation",label:"Depreciation",desc:"Equipment schedule",icon:"D",color:"#18181B"},{type:"labor",label:"Labor",desc:"Hours by technician",icon:"L",color:"#18181B"},{type:"pnl",label:"P&L Statement",desc:"Profit & Loss report",icon:"P",color:"#18181B"}];return e.jsxs("div",{children:[S&&e.jsx(K,{error:!0,className:"mb-4 whitespace-pre-wrap",children:S}),e.jsxs(M,{style:{padding:"24px 28px",marginBottom:20},children:[" ",e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:12},children:[" ",e.jsxs("div",{children:[" ",e.jsx("div",{style:{fontSize:16,fontWeight:500,color:"#09090B",marginBottom:4},children:"Download Complete Tax Package"})," ",e.jsx("div",{style:{fontSize:14,color:"#71717A"},children:"ZIP file with all CSVs + README for your CPA"})," "]})," ",e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[" ",e.jsx(O,{label:"Tax year",className:"min-w-0",children:e.jsxs(ae,{value:x,onChange:v=>$(v.target.value),style:{minWidth:80},disabled:!!i,children:[" ",Array.from({length:new Date().getFullYear()-2023},(v,g)=>String(new Date().getFullYear()-g)).map(v=>e.jsx("option",{value:v,children:v},v))," "]})})," ",e.jsx(E,{onClick:()=>h("tax-package",`waves-tax-package-${x}.zip`),disabled:!!i||l==="tax-package",type:"button",variant:"primary",loading:l==="tax-package",className:"min-w-11",children:"Download ZIP"})," "]})," "]})," "]}),e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:16},children:[" ",e.jsx("span",{style:{fontSize:14,color:"#71717A"},children:"Date range:"})," ",e.jsx(O,{label:"Start date",className:"min-w-0",children:e.jsx(X,{type:"date",value:m,onChange:v=>B(v.target.value),style:{width:130},disabled:!!i})})," ",e.jsx("span",{style:{color:"#71717A",fontSize:14},children:"to"})," ",e.jsx(O,{label:"End date",className:"min-w-0",children:e.jsx(X,{type:"date",value:N,onChange:v=>p(v.target.value),style:{width:130},disabled:!!i})})," "]}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:f?"1fr":"repeat(3, 1fr)",gap:10},children:T.map(v=>e.jsxs(M,{style:{padding:"16px 18px",display:"flex",flexDirection:"column",gap:8},children:[" ",e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[" ",e.jsx("div",{className:"u-nums",style:{width:32,height:32,borderRadius:8,background:`${v.color}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:14,fontWeight:500,color:v.color},children:v.icon})," ",e.jsxs("div",{children:[" ",e.jsx("div",{style:{fontSize:14,fontWeight:500,color:"#09090B"},children:v.label})," ",e.jsx("div",{style:{fontSize:14,color:"#71717A"},children:v.desc})," "]})," "]})," ",e.jsx(E,{onClick:()=>h(v.type,`waves-${v.type}-${m}-to-${N}.csv`),disabled:!!i||l===v.type,style:{marginTop:"auto"},type:"button",variant:"secondary",loading:l===v.type,className:"min-w-11",children:"Download CSV"})," "]},v.type))})," "]})}function ss(){const a=s.useRef(!1),[i,r]=s.useState(""),[S,o]=s.useState(""),f=be(640),[x,$]=s.useState(null),[m,B]=s.useState(null),N=me("/admin/tax/accounts-receivable",$),p=N.loading,l=N.error,y=async g=>{if(!a.current){a.current=!0,r("sendReminder"),o("");try{if(!window.confirm(`Text ${g.customerName} a payment reminder for ${A(g.amount)} (Invoice #${g.invoiceNumber})?`))return;B(g.id);try{await F("/admin/sms/send",{method:"POST",body:JSON.stringify({to:g.phone,message:`Hi ${g.customerName}, it's Waves. You have an outstanding balance of ${A(g.amount)} (Invoice #${g.invoiceNumber}
5). Please call or reply to arrange payment. Thank you!`})}),alert("Reminder sent!")}catch(d){o("Failed to send: "+d.message)}B(null)}finally{a.current=!1,r("")}}};if(p)return e.jsx("div",{style:{padding:40,textAlign:"center",color:"#71717A"},children:"Loading A/R..."});if(l)return e.jsx(ve,{read:N,label:"accounts receivable"});const h=(x==null?void 0:x.summary)||{},T=(x==null?void 0:x.invoices)||[],v=g=>g==="90+"?"#C8312F":g==="60"?"#18181B":g==="30"?"#52525B":"#18181B";return e.jsxs("div",{children:[S&&e.jsx(K,{error:!0,className:"mb-4 whitespace-pre-wrap",children:S})," ",e.jsx("h2",{style:{fontSize:18,fontWeight:500,color:"#09090B",marginBottom:4},children:"Accounts Receivable Aging"})," ",e.jsx("div",{style:{fontSize:14,color:"#71717A",marginBottom:14},children:"Outstanding invoices by aging bucket"}),e.jsxs("div",{style:{display:"flex",gap:10,marginBottom:16,flexWrap:"wrap"},children:[" ",e.jsx(Y,{label:"Total Outstanding",value:A(h.total),color:h.total>500?"#C8312F":"#09090B",sub:`${h.count} invoices`})," ",e.jsx(Y,{label:"Current",value:A(h.current),color:"#18181B"})," ",e.jsx(Y,{label:"30 Days",value:A(h.over30),color:"#52525B"})," ",e.jsx(Y,{label:"60 Days",value:A(h.over60),color:"#18181B"})," ",e.jsx(Y,{label:"90+ Days",value:A(h.over90),color:h.over90>0?"#C8312F":"#09090B"})," "]}),T.length===0?e.jsx("div",{style:{padding:30,textAlign:"center",color:"#71717A",fontSize:14},children:"No outstanding invoices. All caught up!"}):e.jsxs(M,{style:{overflow:"hidden",overflowX:"auto",WebkitOverflowScrolling:"touch"},children:[" ",e.jsxs(Pe,{className:"whitespace-nowrap",style:{minWidth:f?800:void 0},children:[e.jsx(Fe,{children:e.jsx(fe,{children:["Customer","Invoice","Amount","Due Date","Days Overdue","Bucket",""].map(g=>e.jsx(ye,{style:{color:"#71717A",textAlign:"left"},children:g},g))})}),e.jsx(Le,{children:T.map((g,d)=>{const n=g.daysOverdue>=90?"#C8312F11":g.daysOverdue>=60?"#18181B11":g.daysOverdue>=30?"#52525B11":"transparent";return e.jsxs(fe,{style:{background:n,borderBottom:"1px solid #E4E4E722"},children:[e.jsx(V,{style:{color:"#09090B"},children:g.customerName}),e.jsx(V,{style:{color:"#71717A"},children:g.invoiceNumber}),e.jsx(V,{style:{color:"#09090B"},children:A(g.amount)}),e.jsx(V,{style:{color:"#71717A"},children:Z(g.dueDate)}),e.jsxs(V,{style:{color:v(g.bucket)},children:[g.daysOverdue,"d"]}),e.jsx(V,{children:e.jsx(te,{tone:v(g.bucket)==="#C8312F"?"alert":"neutral",children:g.bucket==="90+"?"90+ days":g.bucket==="60"?"60 days":g.bucket==="30"?"30 days":"Current"})}),e.jsx(V,{children:g.phone&&g.daysOverdue>0&&e.jsx(E,{onClick:()=>y(g),disabled:!!i||m===g.id,type:"button",variant:"secondary",loading:m===g.id,className:"min-w-11",children:"Send Reminder"})})]},g.id||d)})})]})," "]})]})}const as={unmatched:"#52525B",matched_expense:"#18181B",matched_payout:"#18181B",created_expense:"#18181B",refund_applied:"#18181B",ignored:"#71717A"},is={unmatched:"review",matched_expense:"expense",matched_payout:"payout",created_expense:"created",refund_applied:"refund",ignored:"ignored"},ls="https://cdn.plaid.com/link/v2/stable/link-initialize.js";let _e=null;function os(){return window.Plaid?Promise.resolve(window.Plaid):(_e||(_e=new Promise((a,i)=>{const r=document.createElement("script");r.src=ls,r.async=!0,r.onload=()=>window.Plaid?a(window.Plaid):i(new Error("Plaid Link did not load")),r.onerror=()=>{_e=null,i(new Error("Could not load Plaid Link"))},document.head.appendChild(r)})),_e)}const qe="waves_plaid_link_resume";function fn(a){try{a?localStorage.setItem(qe,JSON.stringify(a)):localStorage.removeItem(qe)}catch{}}function rs(){try{return JSON.parse(localStorage.getItem(qe)||"null")}catch{return null}}const ds={setup:"Needs setup",active:"Syncing",login_required:"Bank login needed",error:"Last sync failed"};function vn(a){const i=new Date(`${a}T00:00:00Z`);return i.setUTCDate(i.getUTCDate()+1),i.toISOString().slice(0,10)}function jn(a){var i,r;return{plaidModified:((i=a.suggestion)==null?void 0:i.plaidModified)||null,plaidRemoved:((r=a.suggestion)==null?void 0:r.plaidRemoved)||null}}function Ee(a){var i,r;return a.status==="unmatched"&&!((i=a.suggestion)!=null&&i.plaidModified)&&!((r=a.suggestion)!=null&&r.plaidRemoved)}
5function cs(a){if(!a)return"";if(a.error)return`Sync failed: ${a.error}`;if(typeof a.skipped=="string")return`Sync skipped (${a.skipped})`;const i=[`${a.inserted||0} new`];a.updated&&i.push(`${a.updated} updated`),a.deleted&&i.push(`${a.deleted} withdrawn by the bank`),a.flagged&&i.push(`${a.flagged} reviewed rows flagged`);let r=`Synced: ${i.join(", ")}`;return a.matching&&(r+=` — ${a.matching.payoutsLinked} payouts + ${a.matching.expensesLinked} expenses matched`),a.matchingError&&(r+=` — ${a.matchingError}`),r}function us({item:a,existingLabels:i,busy:r,onSave:S,onCancel:o}){const[f,x]=s.useState(()=>a.accounts.map(l=>({...l}))),$=`plaid-labels-${a.id}`,m=vn(je(new Date)),B=l=>{var y;return(y=f.find(h=>h.id===l))==null?void 0:y.syncFrom},N=(l,y)=>x(h=>h.map(T=>T.id===l?{...T,...y}:T)),p=(l,y)=>{const h=i.find(T=>T.label.trim().toUpperCase()===y.trim().toUpperCase());N(l,h?{accountLabel:y,accountType:h.accountType,syncFrom:h.lastDate?vn(h.lastDate):B(l)}:{accountLabel:y})};return e.jsxs("div",{className:"mt-3",children:[e.jsx("datalist",{id:$,children:i.map(l=>e.jsx("option",{value:l.label},l.label))}),e.jsxs(Pe,{children:[e.jsx(Fe,{children:e.jsxs(fe,{children:[e.jsx(ye,{children:"Import"}),e.jsx(ye,{children:"Account"}),e.jsx(ye,{children:"Label"}),e.jsx(ye,{children:"Type"}),e.jsx(ye,{children:"Start date"})]})}),e.jsx(Le,{children:f.map(l=>{const y=i.find(h=>h.label.trim().toUpperCase()===l.accountLabel.trim().toUpperCase());return e.jsxs(fe,{children:[e.jsx(V,{children:e.jsx($e,{checked:l.enabled,onChange:h=>N(l.id,{enabled:h.target.checked}),disabled:r,"aria-label":`Import ${l.name}`})}),e.jsxs(V,{style:{minWidth:180},children:[l.name,l.mask?` ••${l.mask}`:"",e.jsx("div",{className:"text-14 text-ink-secondary",children:l.plaidSubtype||l.plaidType})]}),e.jsxs(V,{children:[e.jsx(X,{list:$,value:l.accountLabel,onChange:h=>p(l.id,h.target.value),disabled:r||!l.enabled,style:{width:240}}),y&&e.jsxs("div",{className:"text-14 text-ink-secondary",children:[y.rows," rows already imported",y.lastDate?`, last ${y.lastDate}`:""]})]}),e.jsx(V,{children:e.jsxs(ae,{value:l.accountType,onChange:h=>N(l.id,{accountType:h.target.value}),disabled:r||!l.enabled,children:[e.jsx("option",{value:"bank",children:"Bank account"}),e.jsx("option",{value:"card",children:"Credit card"})]})}),e.jsx(V,{children:e.jsx(X,{type:"date",value:l.syncFrom,max:m,onChange:h=>N(l.id,{syncFrom:h.target.value}),disabled:r||!l.enabled,title:"Transactions before this date are not imported — set it after the last statement you uploaded by CSV"})})]},l.id)})})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(E,{type:"button",disabled:r,onClick:()=>S(f),children:r?"Saving…":"Save and sync"}),o&&e.jsx(E,{type:"button",variant:"secondary",disabled:r,onClick:o,children:"Cancel"})]})]})}function ps({feedOn:a,onSynced:i}){const[r,S]=s.useState(null),[o,f]=s.useState(""),[x,$]=s.useState(""),[m,B]=s.useState(null),[N,p]=s.useState(null),l=s.useRef(!1),y=s.useCallback(()=>{F("/admin/tax/bank-import/plaid/status").then(d=>{S(d),f("")}).catch(d=>f(d.message))},[]);s.useEffect(()=>{y()},[y]);const h=(d,n)=>{l.current||(l.current=!0,$(d),B(null),Promise.resolve().then(n).catch(b=>B({error:!0,text:b.message})).finally(()=>{l.current=!1,$(""),y()}))},T=(d,n)=>F(d,{method:"POST",body:JSON.stringify(n||{})}),v=d=>{d!=null&&d.sync&&(B({error:!!d.sync.error,text:cs(d.sync)}),i())},g=(d,n=null)=>h(d?`reconnect-${d}`:"connect",async()=>{var Q,_;const[b,P]=await Promise.all([os(),n||T("/admin/tax/bank-import/plaid/link-token",d?{itemId:d}:{})]);fn({linkToken:P.linkToken,itemId:d||null});const z=await new Promise((H,G)=>{const J=b.create({token:P.linkToken,...n?{receivedRedirectUri:n.receivedRedirectUri}:{},onSuccess:(c,q)=>{J.destroy(),H({publicToken:c,metadata:q})},onExit:c=>{J.destroy(),c?G(new Error(c.display_message||c.error_message||"Bank connection was not completed")):H(null)}});J.open()}).finally(()=>fn(null));if(z)if(d)v(await T(`/admin/tax/bank-import/plaid/items/${d}/reconnected`));else{const H=await T("/admin/tax/bank-import/plaid/connect",{publicToken:z.publicToken,institutionName:((_=(Q=z.metadata)==null?void 0:Q.institution)==null?void 0:_.name)||null});p(H.itemId),B({text:"Connected. Confirm each account below, then save to start syncing."})}});return s.useEffect(()=>
5{if(!a||!new URLSearchParams(window.location.search).has("oauth_state_id"))return;const d=window.location.href;window.history.replaceState(null,"",window.location.pathname);const n=rs();n!=null&&n.linkToken?g(n.itemId,{linkToken:n.linkToken,receivedRedirectUri:d}):B({error:!0,text:"The bank sent you back, but this browser no longer has the connection in progress — connect again."})},[a]),o?e.jsxs(K,{error:!0,className:"mb-3",onRetry:y,children:["Could not load bank feeds: ",o]}):!r||!a&&r.items.length===0?null:e.jsxs(M,{style:{padding:16,marginBottom:16},children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-14 font-medium",children:"Live bank feeds"}),e.jsxs("div",{className:"text-14 text-ink-secondary",children:[a?"Read-only via Plaid. New transactions land here every hour for review, the same as an uploaded statement.":"Live bank feeds are switched off — nothing syncs. A connection still in place keeps covering its label's days for statement uploads; disconnect it to import those days from a statement instead.",r.env==="sandbox"?" (Plaid sandbox — test data)":""]})]}),a&&e.jsx(E,{type:"button",disabled:!!x||!r.configured||!r.tokenKey,onClick:()=>g(null),children:x==="connect"?"Connecting…":"Connect a bank"})]}),a&&!r.configured&&e.jsx(K,{className:"mt-3",children:"Plaid keys are not set on the server (PLAID_CLIENT_ID, PLAID_SECRET, PLAID_ENV)."}),r.configured&&!r.tokenKey&&e.jsx(K,{error:!0,className:"mt-3",children:"No encryption key is set (PLAID_TOKEN_KEY), so bank connections cannot be stored."}),m&&e.jsx(K,{error:m.error,className:"mt-3",children:m.text}),r.items.map(d=>e.jsxs("div",{className:"mt-4 border-t border-zinc-200 pt-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-14 font-medium",children:d.institutionName||"Bank connection"}),e.jsx(te,{tone:"neutral",children:ds[d.status]||d.status}),d.lastSyncedAt&&e.jsxs("span",{className:"text-14 text-ink-secondary",children:["Last synced"," ",new Date(d.lastSyncedAt).toLocaleString("en-US",{timeZone:"America/New_York"})]}),e.jsxs("span",{className:"ml-auto flex flex-wrap gap-2",children:[a&&d.status==="login_required"&&e.jsx(E,{type:"button",disabled:!!x,onClick:()=>g(d.id),children:x===`reconnect-${d.id}`?"Opening…":"Log in again"}),a&&d.status!=="setup"&&e.jsxs(e.Fragment,{children:[e.jsx(E,{type:"button",variant:"secondary",disabled:!!x,onClick:()=>h(`sync-${d.id}`,async()=>v(await T(`/admin/tax/bank-import/plaid/items/${d.id}/sync`))),children:x===`sync-${d.id}`?"Syncing…":"Sync now"}),e.jsx(E,{type:"button",variant:"secondary",disabled:!!x,onClick:()=>p(N===d.id?null:d.id),children:"Edit accounts"})]}),e.jsx(E,{type:"button",variant:"secondary",disabled:!!x,onClick:()=>{const n=d.tokenReadable===!1;window.confirm(n?`The stored token for ${d.institutionName||"this bank"} can't be read, so it can't be revoked from here. Only continue if you have already removed this connection in Plaid. Disconnect anyway?`:`Disconnect ${d.institutionName||"this bank"}? Transactions already imported stay; new ones stop.`)&&h(`disconnect-${d.id}`,()=>T(`/admin/tax/bank-import/plaid/items/${d.id}/disconnect`,n?{confirmedRemovedAtPlaid:!0}:{}))},children:"Disconnect"})]})]}),d.tokenReadable===!1&&e.jsx("div",{className:"mt-1 text-14 text-ink-primary",children:"The stored bank token can't be read — check PLAID_TOKEN_KEY on the server. Syncing and revoking are unavailable until it is."}),d.lastError&&d.status!=="active"&&e.jsx("div",{className:"mt-1 text-14 text-ink-secondary",children:d.lastError}),a&&(d.status==="setup"||N===d.id)?e.jsx(us,{item:d,existingLabels:r.existingLabels,busy:x===`setup-${d.id}`,onCancel:d.status==="setup"?null:()=>p(null),onSave:n=>h(`setup-${d.id}`,async()=>{const b=await T(`/admin/tax/bank-import/plaid/items/${d.id}/setup`,{accounts:n.map(P=>({id:P.id,accountLabel:P.accountLabel,accountType:P.accountType,syncFrom:P.syncFrom,enabled:P.enabled}))});p(null),v(b)})},`${d.id}-${d.accounts.map(n=>n.accountLabel).join("|")}`):e.jsx("ul",{className:"mt-2 list-none space-y-1 p-0 text-14",children:d.accounts.map(n=>e.jsxs("li",{children:[n.name,n.mask?` ••${n.mask}`:""," —"," ",n.enabled?`${n.accountLabel} (${n.accountType==="card"?"card":"bank"}) from ${n.syncFrom}`:"not imported"]},n.id))})]},d.id))]})}function ms(){const a=s.useRef(!1),i=s.useRef(0),r=s.useRef(!1),S=s.useRef(0),[o,f]=s.useState({}),[x,$]=s.useState(!0),[m,B]=s.useState(!1),[N,p]=s.useState(0),[l,y]=s.useState({}),[h,T]=s.useState(!1),[v,g]=s.useState(!1),[d,n]=s.useState(0),[b,P]=s.useState([]),[z,Q]=s.useState([]),[_,H]=s.useState(""),[G,J]=s.useState("capone-checking"),[c,q]=s.useState("bank"),[R,j]=s.useState(""),[I,u]=s.useState(null),[C,k]=s.useState({}),[ne,he]=s.useState({}),[Re,De]=s.useState([]),[Ie,Ce]=s.useState(!1),U=je().slice(0,4),[ee,re]=s.useState(U),[se,ke]=s.useState(null),[Oe,We]=s.useState({}),[xe,Ve]=s.useState({}),[ue,He]=s.useState({}),[ze,Ge]=s.useState({}),Me=s.useCallback(t=>{if(t>0&&r.current)return;r.current=!0;
5const w=++i.current;$(!0),t===0&&(P([]),Ce(!1)),f(D=>({...D,rows:null})),F(`/admin/tax/bank-import/transactions?limit=200&offset=${t}${_?`&status=${_}`:""}`).then(D=>{w===i.current&&(P(ie=>t===0?D.transactions||[]:[...ie,...D.transactions||[]]),Ce(!!D.hasMore))}).catch(D=>{w===i.current&&(t===0&&P([]),f(ie=>({...ie,rows:D.message})))}).finally(()=>{w===i.current&&(r.current=!1,$(!1))})},[_]),Se=s.useCallback(()=>{Ve({}),He({}),Ge({}),F("/admin/tax/bank-import/status").then(w=>{y((w==null?void 0:w.counts)||{}),T(!!(w!=null&&w.plaidEnabled)),g(!!(w!=null&&w.enabled)),n((w==null?void 0:w.bankChanges)||0),B(!0),f(D=>({...D,status:null}))}).catch(w=>{B(!1),f(D=>({...D,status:w.message}))}),Me(0);const t=++S.current;F(`/admin/tax/bank-import/coverage?year=${ee}`).then(w=>{t===S.current&&(Q(w.months||[]),f(D=>({...D,coverage:null})))}).catch(w=>{t===S.current&&(Q([]),f(D=>({...D,coverage:w.message})))})},[Me,ee]);s.useEffect(Se,[Se]),s.useEffect(()=>{F("/admin/tax/expense-categories").then(t=>{De(t.categories||[]),f(w=>({...w,categories:null}))}).catch(t=>f(w=>({...w,categories:t.message})))},[N]);const ce=(t,w,D)=>a.current?Promise.resolve():(a.current=!0,j(t),u(null),F(w,{method:"POST",body:JSON.stringify(D||{})}).then(ie=>(Se(),ie)).catch(ie=>{u({error:!0,text:ie.message}),Se()}).finally(()=>{a.current=!1,j("")})),En=t=>{var ie;if(a.current)return;const w=(ie=t.target.files)==null?void 0:ie[0];if(t.target.value="",!w)return;if(!G.trim()){u({error:!0,text:"Set an account label before uploading"});return}ke(null);const D=new FileReader;D.onload=()=>{const Ae={accountLabel:G.trim(),accountType:c,filename:w.name,csv:String(D.result||"")};ce("upload","/admin/tax/bank-import/upload",Ae).then(W=>{var Be;W&&(ke(W.duplicates>0?{...Ae,duplicateRows:W.duplicateRows||[],duplicatesTotal:W.duplicates,forceToken:W.forceToken}:null),We({}),u({text:`Imported ${W.imported} of ${W.parsed} rows (${W.duplicates} already imported, ${W.skippedTotal??W.skipped.length} skipped)`+(W.feedCovered?` — ${W.feedCovered} row${W.feedCovered===1?"":"s"} not imported: a bank feed already covers ${W.feedCovered===1?"that day":"those days"}${W.feedLiveFrom?` (live from ${W.feedLiveFrom})`:""}`:"")+(W.skipped.length?` — skipped: ${W.skipped.slice(0,5).map(ge=>`line ${ge.line} (${ge.reason})`).join("; ")}${(W.skippedTotal??W.skipped.length)>5?` and ${(W.skippedTotal??W.skipped.length)-5} more`:""}`:"")+(W.matching?` · matching linked ${W.matching.payoutsLinked} payouts + ${W.matching.expensesLinked} expenses${W.matching.moreRemaining?" (more rows pending — click Run matching)":""}`:` · ${W.matchingError||"matching not run"}`)+(W.duplicates>0&&((Be=W.duplicateSamples)!=null&&Be.length)?` — skipped as re-uploads: ${W.duplicateSamples.slice(0,3).map(ge=>`${ge.txn_date} ${ge.description.slice(0,24)} $${ge.amount}`).join("; ")}${W.duplicates>3?"…":""}`:"")}))})},D.readAsText(w)},$n=()=>{if(!se)return;const t=(se.duplicateRows||[]).filter(D=>Oe[D.row_hash]).map(D=>D.row_hash);if(!t.length||!window.confirm(`Import the ${t.length} checked row${t.length===1?"":"s"} as ADDITIONAL transactions? Only do this when they were genuinely separate purchases, not a re-upload of the same statement.`))return;const w={...se,forceDuplicates:!0,forceRowHashes:t};ce("upload","/admin/tax/bank-import/upload",w).then(D=>{D&&(ke(null),We({}),u({text:`Force-imported ${D.forced} duplicate row${D.forced===1?"":"s"}`+(D.forceAlreadyPresent?` (${D.forceAlreadyPresent} already force-imported earlier — nothing re-added)`:"")+(D.forceFailed?` · ${D.forceFailed} could NOT be imported (ordinal space exhausted) — add manually via the Expenses tab`:"")}))})};return e.jsxs("div",{children:[Object.entries(o).filter(([,t])=>t).map(([t,w])=>e.jsxs(K,{error:!0,className:"mb-3",onRetry:()=>t==="categories"?p(D=>D+1):Se(),children:["Could not load bank import ",t,": ",w]},t)),x&&e.jsx(K,{children:"Loading bank transactions…"}),e.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap",marginBottom:16},children:[e.jsx(Y,{label:"Needs Review",value:m?l.unmatched||0:"—",color:"#52525B"}),e.jsx(Y,{label:"Matched",value:m?(l.matched_expense||0)+(l.matched_payout||0):"—",color:"#18181B"}),e.jsx(Y,{label:"Created",value:m?l.created_expense||0:"—",color:"#18181B"}),e.jsx(Y,{label:"Refunds",value:m?l.refund_applied||0:"—",color:"#18181B"}),e.jsx(Y,{label:"Ignored",value:m?l.ignored||0:"—"}),d>0&&e.jsx(Y,{label:"Changed by bank",value:d,onClick:()=>H("bank_change")})]}),v&&e.jsx(ps,{feedOn:h,onSynced:Se}),e.jsxs(M,{style:{padding:16,marginBottom:16,display:"flex",gap:10,flexWrap:"wrap",alignItems:"center"},children:[e.jsx(O,{label:"Account label",className:"min-w-0",children:e.jsx(X,{style:{width:180},value:G,onChange:t=>J(t.target.value),placeholder:"Account label (e.g. capone-card-1234)",title:"Stamped on every imported row so checking and each card stay separate",disabled:!!R})}),e.jsx(O,{label:"Account type",className:"min-w-0",children:e.jsxs(ae,{value:c,onChange:t=>q(t.target.value),title:"Card statements book created expenses as 'card'; bank statements as 'ach'",disabled:!!R,children:[e.jsx("option",{value:"bank",children:"Bank account"}),e.jsx("option",{value:"card",children:"Credit card"})]})}),e.jsxs("label",{className:Ln({density:"comfortable",className:"relative cursor-pointer focus-within:ring-2 focus-within:ring-zinc-500"}),children:[R==="upload"?"Importing…":"Upload statement CSV",e.jsx("input",{type:"file",accept:".csv,text/csv",className:"absolute inset-0 h-full w-full cursor-pointer opacity-0",onChange:En,disabled:!!R})]}),e.jsx(E,{type:"button",style:{},disabled:!!R,onClick:()=>ce("match","/admin/tax/bank-import/match").then(t=>{t&&u({text:`Matching pass: ${t.matching.payoutsLinked} payouts + ${t.matching.expensesLinked} expenses linked, ${t.matching.ambiguous} ambiguous${t.matching.moreRemaining?" — more rows pending, run again":""}`})}),variant:"secondary",className:"min-w-11",children:R==="match"?"Matching…":"Run matching"}),e.jsx(E,{type:"button",style:{},disabled:!!R,onClick:()=>{const t=b.filter(w=>{var D,ie;return w.status==="unmatched"&&w.direction==="debit"&&!((D=w.suggestion)!=null&&D.categoryId)&&!((ie=w.suggestion)!=null&&ie.ignore)}).map(w=>w.id).slice(0,50);if(!t.length){u({text:"No uncategorized unmatched debits on screen — load or filter to the rows you want suggestions for"});return}ce("suggest","/admin/tax/bank-import/suggest",{limit:20,ids:t}).then(w=>
5{w&&u({text:`AI suggested categories for ${w.processed} rows`})})},title:"AI proposes an expense category for unmatched debits — nothing is created until you click Create",variant:"secondary",className:"min-w-11",children:R==="suggest"?"Suggesting…":"Suggest categories (AI)"}),e.jsx(O,{label:"Status",className:"min-w-0",children:e.jsxs(ae,{value:_,onChange:t=>H(t.target.value),disabled:!!R,children:[e.jsx("option",{value:"",children:"All statuses"}),e.jsx("option",{value:"unmatched",children:"Needs review"}),e.jsx("option",{value:"matched_expense",children:"Matched to expense"}),e.jsx("option",{value:"matched_payout",children:"Stripe payout"}),e.jsx("option",{value:"created_expense",children:"Created expense"}),e.jsx("option",{value:"refund_applied",children:"Refund applied"}),e.jsx("option",{value:"ignored",children:"Ignored"}),(h||d>0)&&e.jsx("option",{value:"bank_change",children:"Changed by bank"})]})}),e.jsx(O,{label:"Coverage year",className:"min-w-0",children:e.jsx(ae,{value:ee,onChange:t=>re(t.target.value),title:"Coverage year — switch when backfilling a prior tax year",disabled:!!R,children:[0,1,2,3].map(t=>{const w=String(Number(U)-t);return e.jsxs("option",{value:w,children:["Coverage ",w]},w)})})})]}),I&&e.jsxs("div",{role:I.error?"alert":"status",style:{border:`1px solid ${I.error?"#C8312F":"#E4E4E7"}`,background:I.error?"#C8312F11":"#FFFFFF",color:I.error?"#C8312F":"#27272A",borderRadius:8,padding:"8px 14px",fontSize:14,marginBottom:16},children:[I.text,se&&e.jsxs("div",{style:{marginTop:8},children:[e.jsx("div",{style:{color:"#71717A",marginBottom:4},children:"Skipped as re-uploads — check ONLY the rows that were genuinely separate purchases, then import:"}),(se.duplicateRows||[]).map(t=>e.jsxs("label",{style:{display:"block",cursor:"pointer",padding:"1px 0"},className:"ui-choice-label",children:[e.jsx($e,{type:"checkbox",checked:!!Oe[t.row_hash],onChange:w=>We(D=>({...D,[t.row_hash]:w.target.checked})),style:{marginRight:6},disabled:!!R}),t.txn_date," · ",String(t.description).slice(0,40)," · $",t.amount," (",t.direction,")"]},t.row_hash)),(se.duplicatesTotal||0)>(se.duplicateRows||[]).length&&e.jsxs("div",{style:{color:"#71717A",marginTop:4},children:["+",se.duplicatesTotal-se.duplicateRows.length," ","more duplicates not shown — re-upload a smaller slice of the statement to force those"]}),e.jsx(E,{type:"button",disabled:!!R||!!R||!Object.values(Oe).some(Boolean),style:{marginTop:6},onClick:$n,title:"Imports only the checked rows as additional transactions",variant:"secondary",className:"min-w-11",children:"Import selected duplicates"})]})]}),z.length>0&&e.jsx(M,{style:{padding:16,marginBottom:16},children:z.map((t,w)=>e.jsxs("div",{style:{marginBottom:w<z.length-1?10:0},children:[e.jsxs("div",{style:{fontSize:14,color:"#71717A",marginBottom:6},children:[t.month," ledger coverage —"," ",e.jsx("span",{style:{color:"#09090B",fontWeight:500},children:t.pct==null?"—":`${t.pct}%`})," ","of bank outflow is in the expenses ledger ·"," ",A(t.unexplained)," unexplained"]}),e.jsx("div",{style:{height:6,background:"#E4E4E7",borderRadius:3,overflow:"hidden"},children:e.jsx("div",{style:{height:"100%",width:`${t.pct||0}%`,background:(t.pct||0)>=90?"#18181B":"#52525B"}})})]},t.month))}),e.jsxs(M,{style:{overflowX:"auto"},children:[e.jsxs(Pe,{children:[e.jsx(Fe,{children:e.jsx(fe,{style:{color:"#71717A",textAlign:"left"},children:["Date","Account","Description","Amount","Status","Suggestion",""].map(t=>e.jsx(ye,{children:t},t))})}),e.jsxs(Le,{children:[!x&&!o.rows&&b.length===0&&e.jsx(fe,{children:e.jsx(V,{colSpan:7,style:{color:"#71717A",textAlign:"center"},children:"No imported transactions yet — upload a Capital One CSV export to start."})}),b.map(t=>{var w,D,ie,Ae,W,Be,ge,Je,Ke,Xe,Ze,Qe,et,tt,nt,st,at,it,lt,ot,rt,dt,ct,ut,pt,mt,ht,xt,gt,yt,ft,vt,jt,bt,St,wt,Ct,kt,At,Bt,Nt,Tt,Et,$t,Rt,Dt,It,zt,_t,Pt,Ft,Lt,Ot,Wt,Mt,Ut,qt,Yt,Vt,Ht,Gt,Jt,Kt,Xt,Zt,Qt,en,tn,nn,sn,an,ln,on,rn,dn,cn,un,pn,mn,hn,xn;return e.jsxs(fe,{style:{borderBottom:"1px solid #E4E4E7"},children:[e.jsx(V,{style:{whiteSpace:"nowrap"},children:Z(t.txn_date)}),e.jsx(V,{className:"whitespace-nowrap",style:{color:"#71717A"},children:t.account_label}),e.jsx(V,{style:{maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t.description,children:t.description}),e.jsxs(V,{style:{whiteSpace:"nowrap",color:t.direction==="credit"?"#18181B":"#27272A"},children:[t.direction==="credit"?"+":"−",A(t.amount)]}),e.jsx(V,{children:e.jsx(te,{tone:as[t.status]==="#C8312F"?"alert":"neutral",children:is[t.status]||t.status})}),e.jsxs(V,{style:{color:"#71717A",maxWidth:260,overflow:"hidden",
5whiteSpace:"nowrap"},children:[(((w=t.suggestion)==null?void 0:w.plaidModified)||((D=t.suggestion)==null?void 0:D.plaidRemoved))&&e.jsxs("div",{className:"mb-1 text-14 text-ink-primary",style:{whiteSpace:"normal"},children:[t.suggestion.plaidRemoved?"The bank withdrew this transaction.":`The bank changed this to $${Number(t.suggestion.plaidModified.amount).toFixed(2)} ${t.suggestion.plaidModified.direction} on ${t.suggestion.plaidModified.txn_date}${t.status==="unmatched"?".":t.status==="created_expense"?" — edit the expense created from this row to match, then dismiss.":" — unlink to apply it."}`,e.jsxs("span",{className:"ml-2 inline-flex gap-2",children:[t.suggestion.plaidModified&&!t.suggestion.plaidRemoved&&t.status==="unmatched"&&e.jsx(E,{type:"button",variant:"secondary",disabled:!!R,onClick:()=>ce("bank-change",`/admin/tax/bank-import/plaid/rows/${t.id}/bank-change`,{action:"apply",expected:jn(t)}),children:"Apply bank's change"}),e.jsx(E,{type:"button",variant:"secondary",disabled:!!R,onClick:()=>ce("bank-change",`/admin/tax/bank-import/plaid/rows/${t.id}/bank-change`,{action:"dismiss",expected:jn(t)}),children:"Dismiss"})]})]}),(ie=t.suggestion)!=null&&ie.ignore&&!(t.direction==="credit"&&((W=(Ae=t.suggestion)==null?void 0:Ae.refundCandidates)!=null&&W.length||(ge=(Be=t.suggestion)==null?void 0:Be.payoutCandidates)!=null&&ge.length))&&!((Ke=(Je=t.suggestion)==null?void 0:Je.candidates)!=null&&Ke.length)?"internal transfer?":Ee(t)&&((Ze=(Xe=t.suggestion)==null?void 0:Xe.candidates)!=null&&Ze.length||t.direction==="debit"&&(ue[t.id]||(et=(Qe=t.suggestion)==null?void 0:Qe.rejectedExpenseIds)!=null&&et.length||(nt=(tt=t.suggestion)==null?void 0:tt.lastUnlink)!=null&&nt.expenseId))?e.jsx(O,{label:"Match expense",className:"min-w-0",children:e.jsxs(ae,{style:{maxWidth:240},value:C[t.id]||"",onChange:L=>{var de;const le=L.target.value;if(le==="__more_candidates"){const oe=((de=ue[t.id])==null?void 0:de.list)||[];F(`/admin/tax/bank-import/${t.id}/expense-candidates?offset=${oe.length}`).then(pe=>He(Ne=>({...Ne,[t.id]:{list:[...oe,...pe.candidates||[]],total:pe.total??0}}))).catch(pe=>u({error:!0,text:`Could not load matching candidates: ${pe.message}. Choose the load-more option to retry.`}));return}k(oe=>({...oe,[t.id]:le}))},title:"Existing ledger expenses with a matching amount — link instead of creating a duplicate",disabled:!!R,children:[e.jsxs("option",{value:"",children:[(st=t.suggestion)!=null&&st.ignore?"internal transfer? · ":"",(((it=(at=ue[t.id])==null?void 0:at.list)==null?void 0:it.length)??((ot=(lt=t.suggestion)==null?void 0:lt.candidates)==null?void 0:ot.length)??0)>0?`${((dt=(rt=ue[t.id])==null?void 0:rt.list)==null?void 0:dt.length)??t.suggestion.candidates.length} possible existing match${(((ut=(ct=ue[t.id])==null?void 0:ct.list)==null?void 0:ut.length)??t.suggestion.candidates.length)>1?"es":""}…`:"link an existing expense…"]}),(((pt=ue[t.id])==null?void 0:pt.list)||((mt=t.suggestion)==null?void 0:mt.candidates)||[]).map(L=>e.jsxs("option",{value:L.id,children:[(L.vendor_name||L.description||"expense").slice(0,34),L.amount!=null?` · ${A(L.amount)}`:""," ·"," ",Z(L.expense_date)]},L.id)),(ue[t.id]?ue[t.id].list.length<ue[t.id].total:(((ht=t.suggestion)==null?void 0:ht.candidatesTotal)||0)>(((gt=(xt=t.suggestion)==null?void 0:xt.candidates)==null?void 0:gt.length)||0)||!((ft=(yt=t.suggestion)==null?void 0:yt.candidates)!=null&&ft.length))&&e.jsx("option",{value:"__more_candidates",children:(((vt=ue[t.id])==null?void 0:vt.total)??((jt=t.suggestion)==null?void 0:jt.candidatesTotal)??0)>0?`+${(((bt=ue[t.id])==null?void 0:bt.total)??t.suggestion.candidatesTotal)-(((St=ue[t.id])==null?void 0:St.list.length)??(((Ct=(wt=t.suggestion)==null?void 0:wt.candidates)==null?void 0:Ct.length)||0))} more — load…`:"load matching expenses…"})]})}):Ee(t)&&t.direction==="credit"&&((At=(kt=t.suggestion)==null?void 0:kt.refundCandidates)!=null&&At.length||(Nt=(Bt=t.suggestion)==null?void 0:Bt.payoutCandidates)!=null&&Nt.length||(Et=(Tt=t.suggestion)==null?void 0:Tt.rejectedPayoutIds)!=null&&Et.length||(Rt=($t=t.suggestion)==null?void 0:$t.lastUnlink)!=null&&Rt.payoutId||ze[t.id]||xe[t.id])?e.jsx(O,{label:"Match payout or refund",className:"min-w-0",children:e.jsxs(ae,{style:{maxWidth:240},value:C[t.id]||"",onChange:L=>{var de;const le=L.target.value;if(le==="__more_refunds"){const oe=((de=xe[t.id])==null?void 0:de.list)||[];F(`/admin/tax/bank-import/${t.id}/refund-candidates?offset=${oe.length}`).then(pe=>Ve(Ne=>({...Ne,[t.id]:{list:[...oe,...pe.candidates||[]],total:pe.total??0}}))).catch(pe=>u({error:!0,text:`Could not load matching candidates: ${pe.message}. Choose the load-more option to retry.`}));return}if(le==="__more_payouts"){F(`/admin/tax/bank-import/${t.id}/payout-candidates`).then(oe=>Ge(pe=>({...pe,[t.id]:oe.candidates||[]}))).catch(oe=>u({error:!0,text:`Could not load matching candidates: ${oe.message}. Choose the load-more option to retry.`}));return}k(oe=>({...oe,[t.id]:le}))},title:"What is this deposit? Pick the Stripe payout it is, or the original purchase it refunds (applying a refund reduces that expense)",disabled:!!R,children:[e.jsxs("option",{value:"",children:[[(Dt=t.suggestion)!=null&&Dt.ignore?"internal transfer?":null,(zt=(It=t.suggestion)==null?void 0:It.payoutCandidates)!=null&&zt.length?`${t.suggestion.payoutCandidates.length} payout${t.suggestion.payoutCandidates.length>
51?"s":""}`:null,(Pt=(_t=t.suggestion)==null?void 0:_t.refundCandidates)!=null&&Pt.length?`${t.suggestion.refundCandidates.length} original purchase${t.suggestion.refundCandidates.length>1?"s":""}`:null].filter(Boolean).join(" · ")||"link payout / refund","…"]}),!!((Lt=(Ft=t.suggestion)==null?void 0:Ft.payoutCandidates)!=null&&Lt.length||ze[t.id]||(Wt=(Ot=t.suggestion)==null?void 0:Ot.rejectedPayoutIds)!=null&&Wt.length||(Ut=(Mt=t.suggestion)==null?void 0:Mt.lastUnlink)!=null&&Ut.payoutId)&&e.jsxs("optgroup",{label:"Stripe payouts — link",children:[(ze[t.id]||((qt=t.suggestion)==null?void 0:qt.payoutCandidates)||[]).map(L=>e.jsxs("option",{value:`p:${L.id}`,children:[A(L.amount)," · arrived"," ",Z(L.arrival_date)]},`p:${L.id}`)),!ze[t.id]&&((((Yt=t.suggestion)==null?void 0:Yt.payoutCandidatesTotal)||0)>(((Ht=(Vt=t.suggestion)==null?void 0:Vt.payoutCandidates)==null?void 0:Ht.length)||0)||!((Jt=(Gt=t.suggestion)==null?void 0:Gt.payoutCandidates)!=null&&Jt.length))&&e.jsx("option",{value:"__more_payouts",children:(((Kt=t.suggestion)==null?void 0:Kt.payoutCandidatesTotal)||0)>0?`+${t.suggestion.payoutCandidatesTotal-(((Zt=(Xt=t.suggestion)==null?void 0:Xt.payoutCandidates)==null?void 0:Zt.length)||0)} more — load all…`:"load payouts…"})]}),e.jsxs("optgroup",{label:"Original purchases — apply refund",children:[(((Qt=xe[t.id])==null?void 0:Qt.list)||((en=t.suggestion)==null?void 0:en.refundCandidates)||[]).map(L=>e.jsxs("option",{value:`r:${L.id}`,children:[(L.vendor_name||L.description||"expense").slice(0,34)," ","· ",A(L.amount)," · ",Z(L.expense_date)]},`r:${L.id}`)),(xe[t.id]?xe[t.id].list.length<xe[t.id].total:(((tn=t.suggestion)==null?void 0:tn.refundCandidatesTotal)||0)>(((sn=(nn=t.suggestion)==null?void 0:nn.refundCandidates)==null?void 0:sn.length)||0)||!((ln=(an=t.suggestion)==null?void 0:an.refundCandidates)!=null&&ln.length))&&e.jsx("option",{value:"__more_refunds",children:(((on=xe[t.id])==null?void 0:on.total)??((rn=t.suggestion)==null?void 0:rn.refundCandidatesTotal)??0)>0?`+${(((dn=xe[t.id])==null?void 0:dn.total)??t.suggestion.refundCandidatesTotal)-(((cn=xe[t.id])==null?void 0:cn.list.length)??(((pn=(un=t.suggestion)==null?void 0:un.refundCandidates)==null?void 0:pn.length)||0))} more — load…`:"load original purchases…"})]})]})}):((mn=t.suggestion)==null?void 0:mn.categoryName)||""]}),e.jsxs(V,{style:{whiteSpace:"nowrap"},children:[Ee(t)&&t.direction==="debit"&&C[t.id]&&e.jsx(E,{type:"button",disabled:!!R,style:{marginRight:6},onClick:()=>ce("link",`/admin/tax/bank-import/${t.id}/link-expense`,{expenseId:C[t.id]}).then(L=>{L&&k(le=>{const de={...le};return delete de[t.id],de})}),variant:"primary",className:"min-w-11",children:"Link"}),Ee(t)&&t.direction==="credit"&&C[t.id]&&e.jsx(E,{type:"button",disabled:!!R,style:{marginRight:6},onClick:()=>{const L=String(C[t.id]||""),le=L.startsWith("r:"),de=L.slice(2),oe=le?`/admin/tax/bank-import/${t.id}/apply-refund`:`/admin/tax/bank-import/${t.id}/link-payout`;ce(le?"apply-refund":"link-payout",oe,le?{expenseId:de}:{payoutId:de}).then(Ne=>{Ne&&k(Rn=>{const gn={...Rn};return delete gn[t.id],gn})})},variant:"primary",className:"min-w-11",children:String(C[t.id]||"").startsWith("r:")?"Apply refund":"Link payout"}),Ee(t)&&t.direction==="debit"&&!C[t.id]&&e.jsxs(e.Fragment,{children:[e.jsx(O,{label:"Expense category",className:"min-w-0",children:e.jsxs(ae,{style:{maxWidth:170,marginRight:6},value:ne[t.id]||"",onChange:L=>he(le=>({...le,[t.id]:L.target.value})),title:"Category — the AI suggestion is only a default; pick to override",disabled:!!R,children:[e.jsx("option",{value:"",children:(hn=t.suggestion)!=null&&hn.categoryName?`AI: ${t.suggestion.categoryName}`:"Category…"}),Re.map(L=>e.jsx("option",{value:L.id,children:L.name},L.id))]})}),e.jsx(E,{type:"button",disabled:!!R,style:{marginRight:6},onClick:()=>ce("create",`/admin/tax/bank-import/${t.id}/create-expense`,ne[t.id]?{categoryId:ne[t.id]}:{}).then(L=>{L&&he(le=>{const de={...le};return delete de[t.id],de})}),variant:"secondary",className:"min-w-11",children:"Create expense"})]}),t.status==="unmatched"&&e.jsx(E,{type:"button",disabled:!!R,style:{},onClick:()=>ce("ignore",`/admin/tax/bank-import/${t.id}/ignore`),variant:"secondary",className:"min-w-11",children:"Ignore"}),t.status==="ignored"&&!((xn=t.suggestion)!=null&&xn.releasedRefundOf)&&e.jsx(E,{type:"button",disabled:!!R,style:{},onClick:()=>ce("unignore",`/admin/tax/bank-import/${t.id}/unignore`),variant:"secondary",className:"min-w-11",children:"Undo"}),(t.status==="matched_expense"||t.status==="matched_payout"||t.status==="refund_applied")&&e.jsx(E,{type:"button",disabled:!!R,style:{},title:t.status==="refund_applied"?"Undo this refund — restores the adjusted expense and returns the credit to review":"Wrong match? Returns the row to Needs Review; the linked expense/payout itself is untouched",onClick:()=>{window.confirm(t.status==="refund_applied"?"Undo this refund? The adjusted expense is restored.":"Unlink this bank row from its matched ledger record?")&&ce("unlink",`/admin/tax/bank-import/${t.id}/unlink`)},variant:"secondary",className:"min-w-11",children:t.status==="refund_applied"?"Undo refund":"Unlink"}),t.status==="refund_applied"&&e.jsx(E,{type:"button",disabled:!!R,style:{marginLeft:6},title:"Already fixed the expense by hand on the Expenses tab? Clears this refund association WITHOUT touching the expense — the escape hatch when Undo refuses because the expense changed",onClick:()=>{window.confirm("Release this refund WITHOUT restoring the expense? Only after you already corrected the expense manually on the Expenses tab.")&&ce("release",`/admin/tax/bank-import/${t.id}/unlink`,{releaseOnly:!0})},variant:"secondary",className:"min-w-11",children:"Release"})]})]},t.id)})]})]}),Ie&&e.jsx("div",{style:{padding:12,textAlign:"center"},children:e.jsx(E,{type:"button",style:{},onClick:()=>Me(b.length),variant:"secondary",className:"min-w-11",disabled:!!R||x,children:"Load 200 more"})})]})]})}function Cs(){var b,P,z,Q,_,H,G,J,c,q,R,j,I,u,C;const a=be(640),[i,r]=s.useState(()=>new URLSearchParams(window.location.search).has("oauth_state_id")?"bankimport":"overview"),[S,o]=s.useState(!1),f=S?yn.map(k=>k.key==="expenses"?{...k,tabs:[...k.tabs,"bankimport"]}:k):yn,x=f.find(k=>k.tabs.includes(i))||f[0],[$,m]=s.useState(null),[B,N]=s.useState(null),[p,l]=s.useState(null),[y,h]=s.useState(!1),T=s.useCallback(()=>{h(!1),F("/admin/tax/dashboard").then(m).catch(()=>h(!0))},[]);s.useEffect(()=>{F("/admin/tax/bank-import/status").then(k=>o(!!(k!=null&&k.enabled))).catch(()=>{}),T()},[T]);
5const v=me("/admin/tax/pnl?period=mtd",N),g=s.useCallback(k=>l(k==null?void 0:k.summary),[]),d=me("/admin/tax/accounts-receivable",g),n=$;return e.jsxs(Dn,{density:"comfortable",className:"ui-workspace mx-auto max-w-[1300px] text-ui-body text-zinc-900",children:[" ",e.jsx(On,{title:"Taxes",icon:Bn,sections:f.map(k=>{var ne;return k.tabs.includes("advisor")&&((ne=n==null?void 0:n.pendingAlerts)!=null&&ne.high)?{key:k.key,label:`${k.label} (${n.pendingAlerts.high})`,Icon:k.Icon}:{key:k.key,label:k.label,Icon:k.Icon}}),activeKey:x.key,onSectionChange:k=>{const ne=f.find(he=>he.key===k);ne&&r(ne.tabs[0])},navGridClassName:"grid-cols-2 md:grid-cols-4 xl:grid-cols-7",secondarySections:x.tabs.length>1?x.tabs.map(k=>Yn[k]):[],secondaryActiveKey:i,onSecondaryChange:r,secondaryAriaLabel:"Tax sub-section",variant:"workspace"}),!n&&i==="overview"&&e.jsx("div",{style:{padding:48,textAlign:"center",color:y?"#C8312F":"#71717A",fontSize:14},children:y?e.jsxs(e.Fragment,{children:[e.jsx("div",{role:"alert",children:"Could not load the tax overview"}),e.jsx(E,{type:"button",onClick:T,style:{marginTop:12},variant:"secondary",className:"min-w-11",children:"Retry"})]}):"Loading overview…"}),i==="overview"&&v.error&&e.jsx(K,{error:!0,onRetry:v.retry,children:"Could not load the P&L summary."}),i==="overview"&&d.error&&e.jsx(K,{error:!0,onRetry:d.retry,children:"Could not load the receivables summary."}),n&&i==="overview"&&e.jsxs(e.Fragment,{children:[" ",e.jsxs("div",{style:{display:"flex",gap:10,marginBottom:14,flexWrap:"wrap"},children:[" ",e.jsx(Y,{label:"Tax Collected YTD",value:A(n.ytdTaxCollected),color:n.ytdTaxCollected!=null?"#18181B":"#71717A",sub:n.ytdTaxCollected==null?"Not recorded":void 0})," ",e.jsx(Y,{label:"Expenses YTD",value:A((b=n.expenses)==null?void 0:b.total),color:"#52525B",sub:`${((P=n.expenses)==null?void 0:P.count)||0} records`})," ",e.jsx(Y,{label:"Equipment Book Value",value:A((z=n.equipment)==null?void 0:z.bookValue),color:"#18181B",sub:`${((Q=n.equipment)==null?void 0:Q.count)||0} assets`})," ",e.jsx(Y,{label:"Next Deadline",value:(_=n.nextDeadlines)!=null&&_[0]?we(n.nextDeadlines[0].dueDate)<0?`${Math.abs(we(n.nextDeadlines[0].dueDate))}d OVERDUE`:`${we(n.nextDeadlines[0].dueDate)}d`:"—",color:(H=n.nextDeadlines)!=null&&H[0]&&we(n.nextDeadlines[0].dueDate)<=14?"#C8312F":"#18181B",sub:(c=(J=(G=n.nextDeadlines)==null?void 0:G[0])==null?void 0:J.title)==null?void 0:c.substring(0,40)})," "]}),n.latestReport&&e.jsxs(E,{style:{padding:"14px 18px",marginBottom:14,cursor:"pointer"},onClick:()=>r("advisor"),variant:"secondary",className:"!block h-auto w-full text-left whitespace-normal",type:"button",children:[" ",e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:6},children:[" ",e.jsx("span",{style:{fontSize:14,color:"#18181B",fontWeight:500},children:"AI Tax Advisor"})," ",e.jsx("span",{className:"u-nums",style:{fontSize:16,fontWeight:500,color:{A:"#18181B",B:"#18181B",C:"#52525B"}[n.latestReport.grade]||"#71717A"},children:n.latestReport.grade})," ",e.jsx("span",{style:{fontSize:14,color:"#71717A"},children:Z(n.latestReport.date)})," "]})," ",e.jsxs("div",{style:{fontSize:14,color:"#27272A",lineHeight:1.5},children:[(q=n.latestReport.summary)==null?void 0:q.substring(0,200),((R=n.latestReport.summary)==null?void 0:R.length)>200?"...":""]})," "]}),((j=n.nextDeadlines)==null?void 0:j.length)>0&&e.jsxs("div",{style:{marginBottom:14},children:[" ",e.jsx("div",{style:{fontSize:14,fontWeight:500,color:"#09090B",marginBottom:8},children:"Upcoming Deadlines"}),n.nextDeadlines.map(k=>{const ne=we(k.dueDate);return e.jsxs(M,{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",marginBottom:3},children:[" ",e.jsx(te,{tone:Tn[k.status]==="#C8312F"?"alert":"neutral",children:k.status})," ",e.jsx("span",{style:{fontSize:14,color:"#09090B",flex:1},children:k.title})," ",e.jsx("span",{style:{fontSize:14,color:"#71717A"},children:Z(k.dueDate)})," ",e.jsxs("span",{className:"u-nums",style:{fontSize:14,fontWeight:500,color:ne<=7?"#C8312F":ne<=30?"#52525B":"#71717A"},children:[ne,"d"]})," "]},k.id)})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:a?"1fr":"1fr 1fr 1fr",gap:10,marginBottom:14},children:[e.jsxs(E,{onClick:()=>r("pnl"),style:{padding:"14px 18px",cursor:"pointer"},variant:"secondary",className:"!block h-auto w-full text-left whitespace-normal",type:"button",children:[" ",e.jsx("div",{style:{fontSize:14,color:"#71717A",marginBottom:8}
5,children:"Quick P&L (MTD)"}),B?e.jsx("div",{style:{fontSize:14},children:[["Revenue",(I=B.revenue)==null?void 0:I.total,"#27272A"],["COGS",(u=B.cogs)==null?void 0:u.total,"#27272A"],["Gross Profit",B.grossProfit,B.grossProfit>=0?"#18181B":"#C8312F"],["OpEx",(C=B.operatingExpenses)==null?void 0:C.total,"#27272A"],["Net Income",B.netIncome,B.netIncome>=0?"#18181B":"#C8312F"]].map(([k,ne,he])=>e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",padding:"2px 0"},children:[" ",e.jsx("span",{style:{color:"#71717A"},children:k})," ",e.jsx("span",{className:"u-nums",style:{color:he,fontWeight:k==="Net Income"?700:400},children:A(ne)})," "]},k))}):e.jsx("div",{style:{color:"#71717A",fontSize:14},children:"No data yet"})]}),e.jsxs(E,{onClick:()=>r("ar"),style:{padding:"14px 18px",cursor:"pointer"},variant:"secondary",className:"!block h-auto w-full text-left whitespace-normal",type:"button",children:[" ",e.jsx("div",{style:{fontSize:14,color:"#71717A",marginBottom:8},children:"Outstanding A/R"}),p?e.jsxs(e.Fragment,{children:[" ",e.jsx("div",{className:"u-nums",style:{fontSize:22,fontWeight:500,color:p.total>500?"#C8312F":"#09090B",marginBottom:4},children:A(p.total)})," ",e.jsxs("div",{style:{fontSize:14,color:"#71717A"},children:[p.count," unpaid invoice",p.count!==1?"s":""]}),p.over90>0&&e.jsxs("div",{style:{fontSize:14,color:"#C8312F",marginTop:4},children:[A(p.over90)," over 90 days"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"u-nums",style:{fontSize:22,fontWeight:500,color:"#71717A"},children:"—"}),e.jsx("div",{style:{fontSize:14,color:"#71717A"},children:"Not loaded"})]})]}),e.jsxs(M,{style:{padding:"14px 18px",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",gap:8},children:[" ",e.jsx("div",{style:{fontSize:14,color:"#71717A"},children:"CPA Tax Package"})," ",e.jsx(E,{onClick:()=>r("exports"),type:"button",variant:"primary",className:"min-w-11",children:"Download Tax Package"})," ",e.jsx("div",{style:{fontSize:14,color:"#71717A"},children:"ZIP with all CSVs + README"})," "]})," "]})," "]}),i==="rates"&&e.jsx(Vn,{}),i==="services"&&e.jsx(Hn,{}),i==="exemptions"&&e.jsx(Zn,{}),i==="equipment"&&e.jsx(Gn,{}),i==="expenses"&&e.jsx(Jn,{}),i==="bankimport"&&e.jsx(ms,{}),i==="mileage"&&e.jsx(Qn,{}),i==="revenue"&&e.jsx(es,{}),i==="filings"&&e.jsx(Kn,{}),i==="advisor"&&e.jsx(Xn,{}),i==="pnl"&&e.jsx(ts,{}),i==="exports"&&e.jsx(ns,{}),i==="ar"&&e.jsx(ss,{})]})}export{Vn as TaxRatesTab,Cs as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.